码迷,mamicode.com
首页 > 编程语言 > 详细

__proto__ VS. prototype in JavaScript

时间:2019-07-04 00:44:16      阅读:149      评论:0      收藏:0      [点我收藏+]

标签:header   mic   tle   foo   mycat   creation   was   nbsp   span   

__proto__ VS. prototype in JavaScript

http://dmitrysoshnikov.com/ecmascript/javascript-the-core/#a-prototype-chain

// a constructor function
function Foo(y) {
  // which may create objects
  // by specified pattern: they have after
  // creation own "y" property
  this.y = y;
}

 

__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;

 

How does __proto__ differ from constructor.prototype?

 I‘ve been trying to wrap my head around this recently and finally came up with this "map" that I think sheds full light over the matter

技术图片

I know I‘m not the first one making this up but it was more interesting figuring it out that finding it :-). Anyway, after that I found e.g. this another diagram that I think says basicly the same:

Javascript object layout

The most surprising thing for me was discovering that Object.__proto__ points to Function.prototype, instead of Object.prototype, but I‘m sure there‘s a good reason for that :-)

I paste the code mentioned in the image here as well for if anyone wants to test it. Note that some properties are added to the objects for making easy to know where we are after some jumps:

Object.O1=‘‘;
Object.prototype.Op1=‘‘;

Function.F1 = ‘‘;
Function.prototype.Fp1 = ‘‘;

Cat = function(){};
Cat.C1 = ‘‘;
Cat.prototype.Cp1 = ‘‘;

mycat = new Cat();
o = {};

// EDITED: using console.dir now instead of console.log
console.dir(mycat);
console.dir(o);

 

The reason why Object.__proto__ points to Function.prototype is because Object() by itself is a native function that instantiates an empty object. Therefore, Object() is a function. You‘ll find that all the other major native types‘ __proto__ properties point to Function.prototype. Object, Function, String, Number, and Array all inherit the Function prototype.

 

 

JavaScript深入之从原型到原型链 

 

__proto__ VS. prototype in JavaScript

标签:header   mic   tle   foo   mycat   creation   was   nbsp   span   

原文地址:https://www.cnblogs.com/chucklu/p/11129796.html

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