如何定义扩展标准 JavaScript 类(如 Array)的新类

How to define a new class extending standard javascript class like Array?

本文关键字:新类 JavaScript Array 扩展 何定义 定义 标准      更新时间:2023-09-26

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

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]

我知道我可以通过以下方式定义函数删除Dup:

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

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

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

不需要创建一个自己的类:

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

通过引用链接#1,链接#2和链接#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);