I created an object like the following.
var BaseObject = function(){
var base = this;
base.prop;
base.setProp = function(val){
base.prop = val;
}
}
When I call the setProp
method, I get the following.
var a = new BaseObject();
var b = new BaseObject();
a.setProp("foo");
b.setProp("bar");
console.log(a.prop); // outputs 'foo'
console.log(b.prop); // outputs 'bar'
I then created another object that inherits from BaseObject
like this.
var TestObject = function(){
// do something
}
TestObject.prototype = new BaseObject();
When I do the same, I get a result I wasn't expecting.
var a = new TestObject();
var b = new TestObject();
a.setProp("foo");
b.setProp("bar");
console.log(a.prop); // outputs 'bar'
console.log(b.prop); // outputs 'bar'
I don't know why. I've been reading alot about closures and prototypal inheritance recently and I suspect I've gotten it all confused. So any pointers on why this particular example works the way it does would be greatly appreciated.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…