如何定义一个像Array一样扩展标准javascript类的新类?

时间:2014-12-23 12:50:35

标签: javascript

我的理解是"标准"定义新的ClassB扩展ClassA的方法如下:

function ClassA() {
   this.a = {};  // ClassA's instance member.
}
ClassA.prototype.meth1 = function () { .. }  // ClassA's method, shared by all instance.

function ClassB() {}
ClassB.prototype = new ClassA()              // <== "standard" way to extend
ClassB.prototype.meth2 = function () {...}   // ClassB's method

当我尝试定义一个新的类ArrayX时,如下所示:

function ArrayX() {
}
ArrayX.prototype = new Array()
ArrayX.prototype.removeDup = function removeDup() { 
     var o = [];
     for(var j=0; j<this.length; j++) {
          if(notExist(this[j])
              o.push(this[j])
     }
     return o
     function notExist(itm) {
         for(var j=0; j<o.length; j++) {
               if(o[j]===itm)return false
         }
         return true;  
     }

var x = new ArrayX();
console.log(x.length) // returns 0.  Good
console.log(x)        // returns [].  Good
x[0] = 0;
console.log(x);    // returns [].  No good.  I expect x should have one element.
(new ArrayX([1,1,2,3,3])).removeDup()   // I expect returns [1,2,3]

我知道我可以通过以下方式定义function-removeDup:

Array.prototype.removeDup = function removeDup() { ...}

但是,我只想定义一个新类,扩展一些标准的javascript类,比如Array,甚至是DOM类。

那么,如何定义一个新类扩展标准javascript类,如Array?

2 个答案:

答案 0 :(得分:1)

无需创建自己的类:

Array.prototype.myFunction = function(){
   //your custom code
}

答案 1 :(得分:0)

引用link#1link#2&amp; link#3,我试试这个,它按照我的预期运作。

function ArrayX() { 
     // Array.apply(this, arguments)
                                  // calling Array() has same effect as new Array() according to
                                  // [link#3]
                                  // It is no good here.

     this.push.apply(this, arguments); // <-- this works OK. Suggested by link#2

     debugger;                    // Now, `this` has array of value [1, 1, 2, 3, 3], which is
                                  // found in arguments when running new ArrayX(1,1,2,3,3);
                                  // Good.
}
ArrayX.prototype = new Array();   // Suggested by link#1
ArrayX.prototype.removeDup = function removeDup() {
     var o = [];
     for(var j=0; j<this.length; j++) {
          if(notExist(this[j]))
              o.push(this[j])
     }
     return o
     function notExist(itm) {
         for(var j=0; j<o.length; j++) 
              if(o[j]===itm)return false
     }
     return true;  
}
var x = new ArrayX(1,1,2,3,3);  // x is now [1,1,2,3,3].  Good
console.log(x.length)           // 5                      Good
var y = x.removeDup();          // y is [1,2,3].  Good
console.log(y);