码迷,mamicode.com
首页 > 其他好文 > 详细

prototype与__proto__区别

时间:2018-07-06 23:33:53      阅读:341      评论:0      收藏:0      [点我收藏+]

标签:details   stack   eth   var   技术分享   技术   flow   图片   question   

   参考链接: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__区别

标签:details   stack   eth   var   技术分享   技术   flow   图片   question   

原文地址:https://www.cnblogs.com/johnzhu/p/7145008.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!