Javascript, jQuery.extend and "new"
I have a strange behavior while extending a prototype of an object using jQuery.extend.
Assuming this sample class:
var SampleClass = function (anArray) { this.Init(anArray); };
$.extend(SampleClass.prototype, {
array: null,
collection: new Array(),
Init: function (arr) {
var c = this;
开发者_如何学Python c.array = arr;
c.insertInCollection();
},
insertInCollection: function () {
var c = this;
var l = c.array.length;
for (var i = 0; i < l; i++) {
var bar = {};
c.collection.push(bar);
}
alert(c.collection.length);
}
});
Then I execute this sample code
var arr1 = [{ name: 'foo', value: 20 }, { name: 'baz', value: 20}];
var arr2 = [{ name: 'bar', value: 60 }, { name: 'gaz', value: 40}];
c = new SampleClass(arr1);
d = new SampleClass(arr2); //<-- HERE LIES THE PROBLEM
When I create the object "c", the collection gets populated inside the "insertInCollection" function, and the alert returns a length of 2. However, when I instantiate the object "d" (doing a new TestClass(arr2)), the alert inside the "insertInCollection" function is fired and the alert shows 4!
In practice, I can't get what happens in the background. Seems like the elements of the first collection are never deleted - when the second object ("d") is created, it already has the 2 elements of the object "c" existing inside the "collection" property.
This also happens without using jQuery.extend, using the plain .prototype approach.
Anyone can help me with this?
Thank you in advance!
This is happening because every "instance" of SampleClass
is sharing one collection
property: when the insertInCollection()
method accesses the object's collection
property, none is found on the object itself so it uses the collection
property of the object's prototype. To fix this, you need to create a new collection
array for each SampleClass
object. The Init()
method would be a good place to do this:
Init: function (arr) {
var c = this;
c.collection = [];
c.array = arr;
c.insertInCollection();
},
精彩评论