__proto__ VS. prototype in JavaScript

后端 未结 30 2467
爱一瞬间的悲伤
爱一瞬间的悲伤 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
    慢半拍i (楼主)
    2020-11-21 06:37

    As this rightly stated

    __proto__ is the actual object that is used in the lookup chain to resolve methods, etc. prototype is the object that is used to build __proto__ when you create an object with new:

    ( new Foo ).__proto__ === Foo.prototype;
    ( new Foo ).prototype === undefined;
    

    We can further note that __proto__ property of an object created using function constructor points towards the memory location pointed towards by prototype property of that respective constructor.

    If we change the memory location of prototype of constructor function, __proto__ of derived object will still continue to point towards the original address space. Therefore to make common property available down the inheritance chain, always append property to constructor function prototype, instead of re-initializing it (which would change its memory address).

    Consider the following example:

    function Human(){
        this.speed = 25;
    }
    
    var himansh = new Human();
    
    Human.prototype.showSpeed = function(){
        return this.speed;
    }
    
    himansh.__proto__ === Human.prototype;  //true
    himansh.showSpeed();    //25
    
    //now re-initialzing the Human.prototype aka changing its memory location
    Human.prototype = {lhs: 2, rhs:3}
    
    //himansh.__proto__ will still continue to point towards the same original memory location. 
    
    himansh.__proto__ === Human.prototype;  //false
    himansh.showSpeed();    //25
    

提交回复
热议问题