Javavscript change sub-class property on instantia

2019-09-15 15:50发布

if I have

myClass.prototype.subClass=
{
foo:false
}

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();

2条回答
家丑人穷心不美
2楼-- · 2019-09-15 16:47

I think you missunderstand how prototype inheritence works because this question is a bit odd. But you should be able to access the foo property like any other:

newObj.subClass.foo = newValue
查看更多
SAY GOODBYE
3楼-- · 2019-09-15 16:49

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.


Update:

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 = {
        //...
    };
};

and

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);

where inherits is defined as:

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

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

查看更多
登录 后发表回答