Javascript 在实例化时更改子类属性 [英] Javavscript change sub-class property on instantiation

查看:64
本文介绍了Javascript 在实例化时更改子类属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有

myClass.prototype.subClass=
{
foo:false
}

当我在一个对象上创建一个新实例时,如何每次将 foo 设置为不同的值,那么我如何在此处引用该子类

when I create a new instance on an object how can I set foo to a different value each time, so how do I refer to that sub-class here

var newObj = new myclass();

推荐答案

对象和数组不应该添加到原型中除非您想与所有实例共享它们.

Objects and arrays are not something which should be added to the prototype unless you want to share them with all instances.

只要您希望这些对象的属性对于每个实例都不同,您必须将构造函数(或任何其他函数)中的对象分配给特定实例:

As soon as you want properties of these objects to be different for each instances, you have to assign the object in the constructor (or in any other function) to the specific instance:

this.subClass = {
    foo: true
    // potentially other properties
};

也就是说,在某些情况下,原型中有一个默认"对象可能是合理的,但您不应该写入它.

That said, there might be cases were having a "default" object in the prototype might be reasonable, but you should not write to it.

在构造函数中分配对象不会重复代码,而是允许您为每个实例单独更改它.

Assigning the object in the constructor instead does not duplicate code and allows you to change it for each instance individually.

更新:

如果你不想改变原来的构造函数,你可以只在原型中添加一个新函数,并在实例化一个对象时调用它:

If you don't want to change the original constructor, you can either just add a new function to the prototype and call it whenever you instantiate an object:

MyClass.prototype.init = function() {
    this.subClass = {
        //...
    };
};

var obj = new MyClass();
obj.init();

或者你真的创建了一个新的构造函数:

Or you really create a new constructor function:

function MySubClass() {
    MyClass.apply(this, arguments);
    // now create that object for each instance
    this.subClass = {
        foo: someValue
    };
}

inherits(MySubClass, MyClass);

其中 inherits 定义为:

function inherits(Child, Parent) {
    var Tmp_ = function() {};
    Tmp_.prototype = Parent.prototype;
    Child.prototype = new Tmp_();
    Child.prototype.constructor = Child;
}

然后您将使用 MySubClass 而不是 MyClass 来创建实例.

Then you will use MySubClass instead of MyClass to create the instances.

这篇关于Javascript 在实例化时更改子类属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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