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.
There is only one
BaseObjectinstance from which allTestObjects inherit. Don’t use instances for creating prototype chains!What you want is:
See JavaScript inheritance: Object.create vs new, Correct javascript inheritance and What is the reason to use the 'new' keyword at Derived.prototype = new Base for a detailed explanation of the problems with
new. Also have a look at Crockford's Prototypal inheritance – Issues with nested objects