Extend native JavaScript array

后端 未结 10 853
情书的邮戳
情书的邮戳 2020-11-27 22:08

Is there any way to inherit a class from JS native function?

For example, I have a JS function like this:

function Xarray()
{
    Array.apply(this, a         


        
10条回答
  •  温柔的废话
    2020-11-27 22:53

    In your case, a good bet would be to use this pattern:

    function XArray(array) {
      array = array || [];
    
      //add a new method
      array.second = function second() {
        return array[1];
      };
    
      //overwrite an existing method with a super type pattern
      var _push = array.push;
      array.push = function push() {
        _push.apply(array, arguments);
        console.log("pushed: ", arguments);
      };
    
      //The important line.
      return array
    }
    

    Then you can do:

    var list = XArray([3, 4]);
    list.second()   ; => 4
    
    list[1] = 5;
    list.second()   ; => 5
    

    note however that:

    list.constructor  ; => Array and not XArray
    

提交回复
热议问题