Skip to content Skip to sidebar Skip to footer

Javavscript Change Sub-class Property On Instantiation

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-clas

Solution 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:

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

inherits(MySubClass, MyClass);

where inherits is defined as:

functioninherits(Child, Parent) {
    varTmp_ = function() {};
    Tmp_.prototype = Parent.prototype;
    Child.prototype = newTmp_();
    Child.prototype.constructor = Child;
}

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

Solution 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

Post a Comment for "Javavscript Change Sub-class Property On Instantiation"