__proto__ VS. prototype in JavaScript

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

    I know, I am late but let me try to simplify it.

    Let us say there is a function

        function Foo(message){
    
             this.message = message ; 
         };
    
         console.log(Foo.prototype);
    

    Foo function will have a prototype object linked. So,Whenever we create a function in JavaScript, it always has a prototype object linked to it.

    Now let us go ahead and create two objects using the function Foo.

        var a = new Foo("a");
        var b = new Foo("b");
        console.log(a.message);
        console.log(b.message);
    
    1. Now we have two objects, object a and object b. Both are created using constructor Foo. Keep in mind constructor is just a word here.
    2. Object a and b both have a copy of message property.
    3. These two objects a and b are linked to prototype object of constructor Foo.
    4. On objects a and b, we can access Foo prototype using __proto__ property in all browsers and in IE we can use Object.getPrototypeOf(a) or Object.getPrototypeOf(b)

    Now, Foo.prototype, a.__proto__, and b.__proto__ all denotes same object.

        b.__proto__ === Object.getPrototypeOf(a);
        a.__proto__ ===  Foo.prototype;
        a.constructor.prototype  === a.__proto__;
    

    all of above would return true.

    As we know, in JavaScript properties can be added dynamically. We can add property to object

        Foo.prototype.Greet = function(){
    
             console.log(this.message);
        }
        a.Greet();//a
        b.Greet();//b
        a.constructor.prototype.Greet();//undefined 
    

    As you see we added Greet() method in Foo.prototype but it is accessible in a and b or any other object which is constructed using Foo.

    While executing a.Greet(), JavaScript will first search Greet in object a on property list. On not finding , it will go up in __proto__ chain of a. Since a.__proto__ and Foo.prototype is same object, JavaScript will find Greet() method and execute it.

    I hope, now prototype and __proto__ is simplified a bit.

提交回复
热议问题