1. 程式人生 > >prototype與__proto__區別

prototype與__proto__區別

tor .com 技術分享 type defined ani nim lan col

參考鏈接:http://blog.csdn.net/ligang2585116/article/details/53522741

      https://stackoverflow.com/questions/9959727/proto-vs-prototype-in-javascript

一:__proto__和prototype

     

技術分享圖片

技術分享圖片

參考下面的回答:

      

__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

The prototype is a property on a constructor function that sets what will become the __proto__ property on the constructed object.

就是說真正的原型鏈就是通過__proto__來連起來的。

比如下面的例子,animal通過__proto__-->f(){ [native code] }-->object-->null,,一路走到null

function animal(){}

var dog = new animal();

console.log(dog.prototype)  //undefined

console.log(dog.__proto__);  //constructor:f animal()
console.log(animal.prototype) //constructor:f animal()
console.log(animal.__proto__);  //f(){ [native code] }

console.log(animal.prototype === dog.__proto__); //true
console.log(animal.__proto__.__proto__); //Object console.log(animal.__proto__.__proto__.__proto__); //null

console.log(animal.prototype.prototype); //undefined
 

二:修改__proto__

上面直接修改__proto__是不安全的(這東西只是瀏覽器自己實現的一個屬性),正確修改原型的方式像下面這樣:

function inherits(Child, Parent) {
    var F = function () {};
    F.prototype = Parent.prototype;
    Child.prototype = new F();
    Child.prototype.constructor = Child;
}

inherits(Child,Base);

現在可以使用ES6的Object.create 和 Object.setPrototypeOf來修改prototype

prototype與__proto__區別