Reputation: 54001
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.
Upvotes: 0
Views: 81
Reputation: 55759
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.
Upvotes: 1
Reputation: 26
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
.
Upvotes: 0