OOP Javascript - 隔离类中的对象 [英] OOP Javascript - Isolate object within class

查看:107
本文介绍了OOP Javascript - 隔离类中的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个主对象,我可以创建多个实例,每个实例都继承子项(具有唯一/隔离属性)。但是,当我这样做时,对象的属性(在被更改之后)正在改变所有创建的对象。我可能没有正确解释这个,但这个例子应该很清楚。

I'm attempting to have a main object that I can create multiple instances of, that each inherit the children (with unique/isolated properties). When I do this, however, the properties of the object (after being changed) are changing for all created objects. I may not be explaining this correctly, but the example should be pretty clear.

Main = function(){};

// Extending the main class with new object. Doing it this way so I can have these in
// separate files.
Main.prototype.foo = {
    bar: 1
}

// First instance of Main().
var A = new Main();

// Second instance of Main().
var B = new Main();

// Set the bar property to different values for each Main() object.
A.foo.bar = 2;
B.foo.bar = 3;

// Both A.foo.bar and B.foo.bar return 3.
alert(A.foo.bar);
alert(B.foo.bar);

我想要发生的事情,是A.foo.bar返回2和B.foo.bar返回3,这样我就有了彼此独立的孤立对象。

What I'm trying to get to have happen, is for A.foo.bar to return 2 and B.foo.bar to return 3, so that I have isolated objects that are independent of each other.

任何想法?我只是错过了一些明显的东西吗?非常感谢!

Any ideas? Am I just missing something that's obvious? Would be much appreciated!

推荐答案

foo属性在原型对象上,并且只有其中一个。当您通过任何实例设置它时,您正在影响同一个共享属性。

The "foo" property is on the prototype object, and there's only one of those. When you set it via any instance, you're affecting that same shared property.

您可以在构造函数中添加实例属性:

You can add an instance property in your constructor:

  function Main() {
    this.instanceProperty = 1;
  }

然后这将是每个实例。

原型不是主模板或类似的东西;这是一个真实的对象。它不会复制到实例上。相反,运行时知道它就在那里,并且当对实例上实际不存在的实例上的属性进行引用时,它就知道要走原型链并在那里寻找属性。

The prototype is not a "master template" or anything like that; it's a real object. It's not copied onto instances. Instead, the runtime knows it's there, and when references are made to properties on an instance that don't actually exist on the instance, then it knows to walk up the prototype chain and look for properties there.

这篇关于OOP Javascript - 隔离类中的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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