Ways to extend Array object in javascript

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

    You CANNOT extend the Array Object in JavaScript.

    Instead, what you can do is define an object that will contain a list of functions that perform on the Array, and inject these functions into that Array instance and return this new Array instance. What you shouldn't do is changing the Array.prototype to include your custom functions upon the list.

    Example:

    function MyArray() {
      var tmp_array = Object.create(Array.prototype);
      tmp_array = (Array.apply(tmp_array, arguments) || tmp_array);
      //Now extend tmp_array
      for( var meth in MyArray.prototype )
        if(MyArray.prototype.hasOwnProperty(meth))
          tmp_array[meth] = MyArray.prototype[meth];
      return (tmp_array);
    }
    //Now define the prototype chain.
    MyArray.prototype = {
      customFunction: function() { return "blah blah"; },
      customMetaData: "Blah Blah",
    }
    

    Just a sample code, you can modify it and use however you want. But the underlying concept I recommend you to follow remains the same.

提交回复
热议问题