Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
704 views
in Technique[技术] by (71.8m points)

oop - Why are my JavaScript object properties being overwritten by other instances?

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

There is only one BaseObject instance from which all TestObjects inherit. Don't use instances for creating prototype chains!

What you want is:

var TestObject = function(){
    BaseObject.call(this); // give this instance own properties from BaseObject
    // do something
}
TestObject.prototype = Object.create(BaseObject.prototype);

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...