prototype与__proto__区别
参考链接: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