Javascript: create an object that inherits from prototypes of more than one constructor

Let's say I have two constructors:

A = function () {
    this.x = 'x';
};
A.prototype.a = 'a';

B = function () {
    this.y = 'y';
};
B.prototype.b = 'b';

How can I create an ab object that inherits from the prototypes of both of them? so the following example will work:

ab.a === 'a'; // true
ab.b === 'b'; // true
A.prototype.a = 'm';
ab.a === 'm'; // true
B.prototype.b = 'n';
ab.b === 'n'; // true

thank

+3
source share
2 answers

You cannot, there is only one prototype chain. You basically have three options:

Inherit from one, copy another

, , . , , , , .

:

var ab = {
    aness: new A(),
    bness: new B()
};

ab.aness.a === 'a'; // true
ab.bness.b === 'b'; // true
A.prototype.a = 'm';
ab.aness.a === 'm'; // true
B.prototype.b = 'n';
ab.bness.b === 'n'; // true

, ab A ( "A-ness" ) aness B ( "B-ness" ) bness.

, , " ", ( , ). , , .

A-ness B-ness of ab, , . , , , , A foo, - foo B. :

function AB() {
    var aness, bness;

    this.aness = aness = new A();
    this.bness = bness = new B();

    // `foo` returns the `a` property of our composite if
    // it been changed; otherwise, it returns the `b`
    // property of our composite.
    aness.foo = function() {
        // We want to use `A` normal `foo` unless our
        // B-ness `b` property is 42 for some reason.
        if (bness.b === 42) {
            // Our magic number, handle locally.
            return "The answer";
        }
        // Not our magic number, let `A` handle it
        return A.prototype.foo.call(this);
    };
}
var ab = new AB();

, , ab. , .

, .

B A

A B, B A, ab B:

A = function () {
    this.x = 'x';
};
A.prototype.a = 'a';

B = function () {
    this.y = 'y';
};
B.prototype = new A();
B.prototype.b = 'b';

ab = new B();

ab.a === 'a'; // true
ab.b === 'b'; // true
A.prototype.a = 'm';
ab.a === 'm'; // true
B.prototype.b = 'n';
ab.b === 'n'; // true

... , B A, , .


: var , , (, , ).

2. , , (, A B, ).

+7

Source: https://habr.com/ru/post/1776206/


All Articles