Ways to extend Array object in javascript

前端 未结 8 2266
[愿得一人]
[愿得一人] 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:21

    Method names should be lowercase. Prototype should not be modified in the constructor.

    function Array3() { };
    Array3.prototype = new Array;
    Array3.prototype.add = Array3.prototype.push
    

    in CoffeeScript

    class Array3 extends Array
       add: (item)->
         @push(item) 
    

    If you don't like that syntax, and you HAVE to extend it from within the constructor, Your only option is:

    // define this once somewhere
    // you can also change this to accept multiple arguments 
    function extend(x, y){
        for(var key in y) {
            if (y.hasOwnProperty(key)) {
                x[key] = y[key];
            }
        }
        return x;
    }
    
    
    function Array3() { 
       extend(this, Array.prototype);
       extend(this, {
          Add: function(item) {
            return this.push(item)
          }
    
       });
    };
    

    You could also do this

    ArrayExtenstions = {
       Add: function() {
    
       }
    }
    extend(ArrayExtenstions, Array.prototype);
    
    
    
    function Array3() { }
    Array3.prototype = ArrayExtenstions;
    

    In olden days, 'prototype.js' used to have a Class.create method. You could wrap all this is a method like that

    var Array3 = Class.create(Array, {
        construct: function() {
    
        },    
        Add: function() {
    
        }
    });
    

    For more info on this and how to implement, look in the prototype.js source code

提交回复
热议问题