I don't really get JavaScript prototyping. Take this code, for instance:
function Class(asdf) {
if(typeof(asdf) == 'undefined') {
} else {
this.asdf = asdf;
}
}
Class.prototype.asdf = "default_asdf";
Class.prototype.asdf2 = [];
Class.prototype.change_asdf = function() {
this.asdf = "changed_asdf";
this.asdf2.push("changed_asdf2");
}
function SubClass() {
}
SubClass.prototype = new Class("proto_class");
SubClass.prototype.constructor = SubClass;
test1 = new SubClass();
alert("test1 asdf: " + test1.asdf + " " + test1.asdf2);
test1.change_asdf();
alert("test1 asdf: " + test1.asdf + " " + test1.asdf2);
test2 = new SubClass();
alert("test2 asdf: " + test2.asdf + " " + test2.asdf2);
The first alert prints "proto_class []", as expected. The second alert prints "changed_asdf [changed_asdf2]", also as expected. But why does the third alert print "proto_class [changed_asdf2]"?! If the original prototype object (new Class("proto_class")) is being modified, then why doesn't the asdf variable remain "changed_asdf"? And if it isn't, then why does the asdf2 array contain "changed_asdf2"? Furthermore, how do I make sure that each new SubClass() instance contains a fresh instance of Class(), as in C++ and Java?