inheritance - Unable to extend javascript prototype -


i playing around idea of subclassing javascript. pretend extending native objects (like array, string etc) bad idea. this, true, out of understanding why.

having said that, let's on it.

what i'm trying extend array (now, extend may not right term i'm doing)

i want create new class myarray , want have 2 methods on it. .add , .addmultiple.

so implemented this.

function myarray(){     var arr = object.create(array.prototype);     return array.apply(arr, arguments); }  myarray.prototype = array.prototype;  myarray.prototype.add = function(i){     this.push(i); }  myarray.prototype.addmultiple = function(a){     if(array.isarray(a)){         for(var i=0;i<a.length;i++){             this.add(a[i]);         }     } } 

this works correctly, if do

console.log(array.prototype.addmultiple ); console.log(array.prototype.add); 

i [function] , [function]. means code modifying native array object. trying avoid. how change code in way 2 console.logs give me undefined still able use native array.prototype methods .push?

tia

you should setup proper prototypes chain:

function myarray(){     array.apply(this, arguments); }  myarray.prototype = object.create(array.prototype); 

object.create creates new object specified prototype, after operation following true:

myarray.prototype !== array.prototype; // true object.getprototypeof(myarray.prototype) === array.prototype; // true 

Comments

Popular posts from this blog

java - Jasper subreport showing only one entry from the JSON data source when embedded in the Title band -

serialization - Convert Any type in scala to Array[Byte] and back -

SonarQube Plugin for Jenkins does not find SonarQube Scanner executable -