Extended built-in objects

By the prototype object, the original built-in objects custom extension method. For example, to add custom array functions sum

Array prototype had no sum sum method, the prototype for the Array add new methods in the following form

 Array.prototype.sum = function() {
        was Sum 0
        for (var i = 0; i < this.length; i++) {
          sum += this[i]
        }
        return sum
      }
      var arr = new Array(1, 2, 3)
      console.log(arr.sum()) // 6
You can see, you can use the newly created array sum method you just added. We can also print it Array prototype

 

 You can see the sum method has been added to the Array prototype.

Extended:

He said before adding method can also be used in another way.

      Array.prototype = {
        sum: function() {
          was Sum 0
          for (var i = 0; i < this.length; i++) {
            sum += this[i]
          }
          return sum
        }
      }
So could it not?

 

Of course, it is not enough. So write the original prototype comes with Array will cover method, which is not allowed. 

Guess you like

Origin www.cnblogs.com/perse/p/12040219.html