__proto__ VS. prototype in JavaScript

后端 未结 30 2456
爱一瞬间的悲伤
爱一瞬间的悲伤 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:43

    prototype is a property of a Function object. It is the prototype of objects constructed by that function.

    __proto__ is internal property of an object, pointing to its prototype. Current standards provide an equivalent Object.getPrototypeOf(O) method, though de facto standard __proto__ is quicker.

    You can find instanceof relationships by comparing a function's prototype to an object's __proto__ chain, and you can break these relationships by changing prototype.

    function Point(x, y) {
        this.x = x;
        this.y = y;
    }
    
    var myPoint = new Point();
    
    // the following are all true
    myPoint.__proto__ == Point.prototype
    myPoint.__proto__.__proto__ == Object.prototype
    myPoint instanceof Point;
    myPoint instanceof Object;
    

    Here Point is a constructor function, it builds an object (data structure) procedurally. myPoint is an object constructed by Point() so Point.prototype gets saved to myPoint.__proto__ at that time.

提交回复
热议问题