function Resource(){
var id = '';
this.getId = function(){
return id;
}
this.setId = function(value){
id = value;
}
}
function Model(){ }
Model.prototype = new Resource();
To test the above code, I have the following:
var m1 = new Model();
m1.setId("blah");
alert("m1 = " + m1.getId());
var m2 = new Model();
m2.setId("blahblah");
alert("m2 = " + m2.getId());
alert("m1 = " + m1.getId());
I would expect the following to be alerted: m1 = blah, m2 = blahblah, m1 = blah.
However, the following is being displayed: m1 = blah, m2 = blahblah, m1 = blahblah.
I have written the above code as an experiment so that I can begin to understand inheritance in JavaScript. Perhaps my expectation of what should be displayed is due to my Java/C# background. Clearly each new Model object created shares the same id variable defined in Resource. Why is this?
How can I write this so that each new Model can have its own unique id (other than the obvious – defining in within Model)?
BTW, I have purposely definted id as var id rather than this.id, as I am looking for the private-variable behavior.
A prototype object is shared among all instances.
Because the
idvariable belongs to theResourceconstructor, and because theprototypeofModelis that single instance ofResource, all theModelinstances are using that single instance, and therefore the same variable.For each
Modelinstance to have its ownidvariable, you’ll need to create theidvariable in theModelconstructor, as well as the accessor methods.Another way to accomplish this is to invoke
Resourceusing theModelinstances as the context. This is done using.callor.applylike this:This will invoke the
Resourcefunction, which will create theidvariable and its accessor methods, but the accessors will be assigned to theModelinstance.