__proto__ VS. prototype in JavaScript

后端 未结 30 1908
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-21 06:14

This figure again shows that every object has a prototype. Constructor function Foo also has its own __proto__ which is Function.prototype, a

30条回答
  •  悲&欢浪女
    2020-11-21 06:53

    Summary:

    The __proto__ property of an object is a property that maps to the prototype of the constructor function of the object. In other words:

    instance.__proto__ === constructor.prototype // true

    This is used to form the prototype chain of an object. The prototype chain is a lookup mechanism for properties on an object. If an object's property is accessed, JavaScript will first look on the object itself. If the property isn't found there, it will climb all the way up to protochain until it is found (or not)

    Example:

    function Person (name, city) {
      this.name = name;
    }
    
    Person.prototype.age = 25;
    
    const willem = new Person('Willem');
    
    console.log(willem.__proto__ === Person.prototype); // the __proto__ property on the instance refers to the prototype of the constructor
    
    console.log(willem.age); // 25 doesn't find it at willem object but is present at prototype
    console.log(willem.__proto__.age); // now we are directly accessing the prototype of the Person function 

    Our first log results to true, this is because as mentioned the __proto__ property of the instance created by the constructor refers to the prototype property of the constructor. Remember, in JavaScript, functions are also Objects. Objects can have properties, and a default property of any function is one property named prototype.

    Then, when this function is utilized as a constructor function, the object instantiated from it will receive a property called __proto__. And this __proto__ property refers to the prototype property of the constructor function (which by default every function has).

    Why is this useful?

    JavaScript has a mechanism when looking up properties on Objects which is called 'prototypal inheritance', here is what it basically does:

    • First, it's checked if the property is located on the Object itself. If so, this property is returned.
    • If the property is not located on the object itself, it will 'climb up the protochain'. It basically looks at the object referred to by the __proto__ property. There, it checks if the property is available on the object referred to by __proto__.
    • If the property isn't located on the __proto__ object, it will climb up the __proto__ chain, all the way up to Object object.
    • If it cannot find the property anywhere on the object and its prototype chain, it will return undefined.

    For example:

    function Person (name) {
      this.name = name;
    }
    
    let mySelf = new Person('Willem');
    
    console.log(mySelf.__proto__ === Person.prototype);
    
    console.log(mySelf.__proto__.__proto__ === Object.prototype);

提交回复
热议问题