WinJS.Class – unexpected behavior – watch out

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();
test1.test.push(1);
var test2 = new TestClass();
test2.test.push(1);
var len = test2.test.length;

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


%d bloggers like this: