为什么我的JavaScript对象属性被其他实例覆盖? [英] Why are my JavaScript object properties being overwritten by other instances?

查看:79
本文介绍了为什么我的JavaScript对象属性被其他实例覆盖?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个如下对象。

I created an object like the following.

var BaseObject = function(){

var base = this;
base.prop;

base.setProp = function(val){
    base.prop = val;
}
}

当我调用 setProp时方法,我得到以下内容。

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'

然后我创建了另一个继承自 BaseObject的对象喜欢这个。

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.

推荐答案

只有一个 BaseObject 实例,所有 TestObject s继承。不要使用实例来创建原型链!

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

你想要的是:

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

参见 JavaScript继承:Object.create vs new 正确的javascript继承在Derived.prototype = new Base 上使用'new'关键字的原因是什么,以详细解释 new 的问题。另请参阅 Crockford的Prototypal继承 - 嵌套对象的问题

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

这篇关于为什么我的JavaScript对象属性被其他实例覆盖?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆