简体   繁体   中英

Object extending Array with Functional Inheritance

Using functional inheritance we can extend objects by passing them as the context of a function call assigning to this .

This doesn't seem to work as I'd expect for the Array constructor.

var ctx = {
    foo: "foo"
};

Array.call(ctx);

ctx -> Object(foo: "foo")

Conversely this does work with other constructor looking functions.

var fakeArrayConstructor = function () {
    this.length = 5;
}

fakeArrayConstructor.call(ctx);

ctx -> Object {foo: "foo", length: 5}

Does the Array constructor not assign some of its properties using this or is there something else going on? I know that a lot of the functionality associated with arrays is stored on Array.prototype however that's not my focus for this exercise.

Functional Inheritance in the linked article is not using call .

Please correct me if I am wrong. The Array function happens to have a peculiar implementation, but that is orthogonal to this question. In order to make functional inheritance work, constructor functions need to be written to support it.

Your Array.call approach is sometimes used to simulate inheritance, but this approach requires methods to be assigned to the instance from directly inside the constructor function, which is probably the exception rather than the rule in most cases.

Firstly, functional inheritance allows you to avoid reference to the this keyword all together. The example you linked clearly shows that.

The Array global object is implementation defined but we can assume that all properties are assigned to __proto__ and not this .

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