Reputation: 11
I am new to learning inheritance concept in JavaScript. In this context, I would like to inherit the Array object and add functionalities to it.
The problem that I face here is that third
method is getting executed correctly, but the show()
method throws an error, stating that show()
is not a function.
var a = [1,2,3,4,5];
Array.prototype = {
third:function(){
console.log(a[3]);
},
show:function(){
console.log(a);
}
};
a.third();
a.show();
Upvotes: 0
Views: 71
Reputation: 147363
The problem is that your code is attempting to replace the built–in prototype (which itself is an Array) with a plain object that only has the properties you assign. Instead of replacing the prototype, add properties to the one that's already there, e.g.
Array.prototype.third = function() {
console.log(a[3]);
}
Also, since you create the a array before replacing Array.prototype, it get's the old prototype, not the new one (if the new one is added at all). Both methods throw errors, not just show. If you change the prototype before creating a, it "works" in browsers that allow overwriting of built–in prototypes. It will not work in ECAMScript ed 3 (or perhaps earlier) implementation or later where Array.prototype has attributes:
{ [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false }
so you can't replace it and the object itself has attributes:
{ [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: false }
so you can add properties and overwrite built–in methods if you wish.
Note that extending built–in objects is generally warned against, see Extending builtin natives. Evil or not?.
Upvotes: 2
Reputation: 63524
If you're going to be adding methods to native prototypes, you really need to put a check in place so that you can be sure you're not overriding anything important. So, to take your example and change it up a little:
if (!('third' in Array.prototype)) {
Array.prototype.third = function () {
return this[2];
};
}
[0, 1, 2, 3].third(); // 2
Upvotes: 0
Reputation: 1297
Instead of that, try this way:
var array = [1,2,3,4,5];
Array.prototype.third = function () { console.log(this[3]); }
Array.prototype.show = function () { console.log(this); }
array.third();
array.show();
Upvotes: 0