1

What's wrong with this code? I'm trying to extend the class foo with all the native array's functions.

function foo(){
    Array.call(this);
 }

foo.prototype.addFruit=function(item){
    this.unshift(item);
}
foo.prototype=new Array();
foo.prototype.constructor=foo;

var c =new foo();

c.addFruit('Apple');


document.write(c.join('-'));
​

2 Answers 2

2

You add the method addFruit to the prototype of foo, then you overwrote the the foo.prototype, so the method is missing (The prototype changed to another object after you put a method to the original prototype).

You should change your order of the code, assign the prototype before add method to prototype.

foo.prototype=new Array();
foo.prototype.constructor=foo;

foo.prototype.addFruit=function(item){
    this.unshift(item);
};
Sign up to request clarification or add additional context in comments.

Comments

2

You add the addFruit property to the prototype before you overwrite the whole prototype property with a new Array.

Instead of new Array, you should use Object.create(Array.prototype) so you don't have an actual Array instance as the prototype (with length etc) but only an object inheriting from the Array prototype.

Array.call(this) unfortunately does not work. It returns a new array, which is assigned to nothing, but it does not do anything on this. You can check by this !== Array.call(this). Actually, it is not possible to "subclass" Array - read on http://perfectionkills.com/how-ecmascript-5-still-does-not-allow-to-subclass-an-array

2 Comments

thanks but what is the difference between foo.prototype=Object.create(Array.prototype); and foo.prototype=Array.prototype;
The second one assigns one to the other, so that foo.prototype === Array.prototype, while Object.create creates a new object with a properly set-up prototype chain.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.