Archive for the ‘WinJS’ Category

WinJS.Class – unexpected behavior – watch out

January 3, 2013

What would you expect the code below to produce for value of ‘len’? If you said 1, then you, like me, are incorrect! In fact the value is 2. The problem here is that instance members get added to the prototype. So the array ‘test’ gets added to the prototype and both instances of TestClass are working on the same array. This seems very strange and is not clear from the documentation at: WinJS.Class.define. To avoid this issue, the test array must be initialized in the constructor.

var TestClass = WinJS.Class.define(function () {
// constructor
}, {
// instance members
test: []
}, {
// static members

var test1 = new TestClass();
var test2 = new TestClass();
var len = test2.test.length;