modifying class properties with John Resigs simple javascript inheritance
Currently I'm trying to use John Resigs Simple Javascript Inheritence开发者_C百科 library, this works great but when I try to modify default member variables, it seems to influence the prototype rather than only the instance:
http://jsfiddle.net/u2MWL/1/
As you can see, the events is of different length each time you create a new instance. Am I using the library in the wrong way or is this a known flaw? What are the alternatives?
The problem here is that you are extending the class with events: []
Array (and {}
object) variables are references. So by extending the class with an array, every instance of the class is going to have an events
equal to the same referenced array.
To get around this you could do
var Test = Class.extend({
events: null,
init: function() {
this.events = [];
this.events.push(1);
alert(this.events.length);
},
say: function(words) {
}
});
This way, each time a class is initialized a new array (thus reference) is appointed to events
. Not elegant, I know, but it should work.
精彩评论