关于__proto__的链式记忆

实例化解析:

function Foo() {};

var foo = new Foo();
foo.__proto__ === Foo.prototype;
foo.__proto__.__proto__ === Object.prototype;
foo.__proto__.__proto__.__proto__ === null;
foo.prototype === undefined;
foo.toString === Object.prototype.toString;

原形继承后的实例化解析:

function Bar() {};

Bar.prototype.__proto__ = Foo.prototype;

var bar = new Bar();
bar.__proto__ === Bar.prototype;
bar.__proto__.__proto__ === Foo.prototype;
bar.__proto__.__proto__.__proto__ === Object.prototype;
bar.__proto__.__proto__.__proto__.__proto__ === null;
bar.prototype === undefined;
bar.toString === Object.prototype.toString

对象bar,访问toString,整个链式过程如下:

bar.toString 
    || bar.__proto__.toString 
    || bar.__proto__.__proto__.toString
    || bar.__proto__.__proto__.__proto__.toString 

bar.toString === Object.prototype.toString

最终调用的是 Object.prototype.toString

奇怪的Foo.toString

Foo.__proto__ === Function.prototype;
Foo.__proto__.__proto__ === Object.prototype;
Foo.prototype.__proto__ === Object.prototype;
// 神奇竟然不等于 Object.prototype.toString
Foo.toString === Object.toString;
Foo.prototype.toString === Object.prototype.toString;

每个function生成的时候都直接被设置了toString 等于 Object.toString了。

参考文档

有爱

希望本文对你有用 ^_^

posted @ 2011-11-02 15:02  MK2  阅读(514)  评论(0编辑  收藏  举报