Ways to extend Array object in javascript

前端 未结 8 2180
[愿得一人]
[愿得一人] 2020-12-13 13:02

i try to extend Array object in javascript with some user friendly methods like Array.Add() instead Array.push() etc...

i implement 3 ways to do this. unfortunetly t

相关标签:
8条回答
  • 2020-12-13 13:32
    var SubArray = function() {                                           
        var arrInst = new Array(...arguments); // spread arguments object
        /* Object.getPrototypeOf(arrInst) === Array.prototype */
        Object.setPrototypeOf(arrInst, SubArray.prototype);     //redirectionA
        return arrInst; // now instanceof SubArray
    };
    
    SubArray.prototype = {
        // SubArray.prototype.constructor = SubArray;
        constructor: SubArray,
    
        // methods avilable for all instances of SubArray
        add: function(element){return this.push(element);},
        ...
    };
    
    Object.setPrototypeOf(SubArray.prototype, Array.prototype); //redirectionB
    
    var subArr = new SubArray(1, 2);
    subArr.add(3); subArr[2]; // 3
    

    The answer is a compact workaround which works as intended in all supporting browsers.

    0 讨论(0)
  • 2020-12-13 13:40

    In your third example you're just creating a new property named prototype for the object Array3. When you do new Array3 which should be new Array3(), you're instantiating that object into variable list3. Therefore, the Add method won't work because this, which is the object in question, doesn't have a valid method push. Hope you understand.

    Edit: Check out Understanding JavaScript Context to learn more about this.

    0 讨论(0)
提交回复
热议问题