__proto__ VS. prototype in JavaScript

后端 未结 30 1968
爱一瞬间的悲伤
爱一瞬间的悲伤 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条回答
  •  梦毁少年i
    2020-11-21 06:55

    There is only one object that is used for protypal chaining. This object obviously has a name and a value: __proto__ is its name, and prototype is its value. That's all.

    to make it even easier to grasp, look at the diagram on the top of this post (Diagram by dmitry soshnikov), you'll never find __proto__ points to something else other than prototype as its value.

    The gist is this: __proto__ is the name that references the prototypal object, and prototype is the actual prototypal object.

    It's like saying:

    let x = {name: 'john'};
    

    x is the object name (pointer), and {name: 'john'} is the actual object (data value).

    NOTE: this just a massively simplified hint on how they are related on a high level.

    Update: Here is a simple concrete javascript example for better illustration:

    let x = new String("testing") // Or any other javascript object you want to create
    
    Object.getPrototypeOf(x) === x.__proto__; // true
    

    This means that when Object.getPrototypeOf(x) gets us the actual value of x (which is its prototype), is exactly what the __proto__ of x is pointing to. Therefore __proto__ is indeed pointing to the prototype of x. Thus __proto__ references x (pointer of x), and prototype is the value of x (its prototype).

    I hope it's a bit clear now.

提交回复
热议问题