Javavscript change sub-class property on instantia

2019-09-15 16:25发布

问题:

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

回答1:

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.



回答2:

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