简体   繁体   中英

inherit sub-object together with object

I'm using objects A and AB with

A.myB = A.B;

I have an inherited A1 and A1.B where A1.B is inherited from AB and

A1.myB = A1.B;

The code to achieve this looks like this:

A = function() {
    this.myB = this.createB();
};
...
A.prototype.createB = function() {
    return new A.B();
};

Then on inheriting AI need to change .createB :

A1.prototype.createB = function() {
    return new A1.B1();
};

I think I'm overlooking something - is there a more straightforward way to set this up, without the need for changing createB ?

Alright, while writing this I found an answer. Maybe helpful for anyone out there:

A.prototype.createB = function() {
    return new this.constructor.B();
};

I think that should do the trick and may be quite handy in combination with the subobject being defined as a property of the main objects constructor.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM