Ways to extend Array object in javascript

前端 未结 8 2293
[愿得一人]
[愿得一人] 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.

提交回复
热议问题