Prototype keyword in Javascript

后端 未结 3 960
太阳男子
太阳男子 2020-12-12 21:41

What is prototype property, and why is it necessary? So far, I have learnt that this provides public access to more intrinsic, and private prototype

3条回答
  •  有刺的猬
    2020-12-12 22:41

    In JavaScript, function objects have a built-in .prototype property. The value of this property is an object. If the function is used as a constructor, the resulting instances inherit from that "prototype" object.

    Example:

    var Dog = function () {}; // the constructor function
    
    Dog.prototype.bark = function () {}; // adding a method to Dog.prototype
    
    var dog1 = new Dog; // creating a new instance
    
    dog1.bark(); // the instance inherits the "bark" method from Dog.prototype
    

    Note that the .prototype property (of function objects) is not the same as the [[Prototype]] internal property. All objects contain the latter. It's an internal reference to an object's prototype. (In the above example, the dog1 object's [[Prototype]] refers to Dog.prototype.) On the other hand, only function objects have a built-in .prototype property (which makes sense since only function objects can be used as constructors).

提交回复
热议问题