__proto__ VS. prototype in JavaScript

__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深入之从原型到原型链 

 

作者:Chuck Lu    GitHub    
posted @   ChuckLu  阅读(178)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
历史上的今天:
2018-07-03 同一个站点下,兼容不同版本的JQuery Can I use multiple versions of jQuery on the same page?
2018-07-03 DataTables
2017-07-03 ControlDesigner
2015-07-03 CodeWars可以学习的
2015-07-03 Number of Rectangles in a Grid
2014-07-03 同步TreeView中父结点和子结点的状态[以及Treeview的bug]
点击右上角即可分享
微信分享提示