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

查看:21
本文介绍了为什么我的 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 都从它继承.不要使用实例来创建原型链!

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 的原型继承 - 嵌套对象问题

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天全站免登陆