Array.length vs Array.prototype.length

前端 未结 4 1930
Happy的楠姐
Happy的楠姐 2020-12-19 15:20

I found that both the Array Object and Array.prototype have the length property. I am confused on using the Array.length

4条回答
  •  执笔经年
    2020-12-19 15:57

    If you have an instance of an Array, it inherits all properties from the Array.prototype thanks to Javascript's use of prototypical inheritance.

    Take the following example:

    function MyClass() {
      this.foo = Math.random();
    }
    
    MyClass.prototype.getFoo = function() {
      return this.foo;
    }
    
    // Get and log
    var bar = new MyClass();
    console.log(bar.getFoo());

    This declares a function (serving as the constructor) for a class. That function provides the prototype for each instance of the class. When we assign a method (getFoo) to that prototype, every instance of the class will have the method.

    You can then call the method on an instance and it will be applied to the data that class contains. In the case of arrays, the length property will get the length of the array you call it on:

    [1, 2, 3, 4].length == 4; // Every array has a length
    

    However, because functions behave largely like objects and may have their own properties, Array itself may have properties. That is what you see when using Array.length, which gets the number of parameters the Array (constructor) function expects to receive. Every function has a length property.

提交回复
热议问题