作者: Laruence 之前我对Javascript的原型链中, 原型继承与标识符查找有些迷惑, 如, 如下的代码:1
2
3
4
5function Foo() {};
var foo = new Foo();
Foo.prototype.label = "laruence";
alert(foo.label); //output: laruence
alert(Foo.label);//output: undefined
今天看到了如下这个图:
另外, 在Javascript Object Hierarchy看到:
The prototype is only used for properties inherited by objects/instances created by that function. The function itself does not use the associated prototype.
也就是说, 函数对象的prototype并不作用于原型链查找过程中, 今天在firefox下发现(因为firefox通过__proto__暴露了[[prototype]]), 真正参与标识符查找的是函数对象的__proto__,1
2
3
4
5function Foo() {};
var foo = new Foo();
Foo.\_\_proto\_\_.label = "laruence";
alert(Foo.label); //output: laruence
alert(foo.label);//output: undefined
而, 显然的:1
2function Foo() {};
alert(Foo.\_\_proto\_\_ === Foo.prototype); //output: false
另外, 也解释了,1
2
3
4
5
6
7
8
9
10
11
12
13
14 alert(Object.forEach); // undefined
Function.prototype.forEach = function(object, block, context) {
for (var key in object) {
if (typeof this.prototype\[key\] == "undefined") {
block.call(context, object\[key\], key, object);
}
}
};
alert(Object.forEach);
alert(Function.forEach);
alert(Object.forEach === Function.forEach); // true
本文链接: https://erik.xyz/2015/01/05/javascript-yuan-xing-lian-he-yuan-xing-de-yi-ge-wu-qu/
版权声明: 本作品采用 知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议 进行许可。转载请注明出处!