菜单

Javascript原型链和原型的一个误区

2015-01-05 - 优秀原创

作者: Laruence

之前我对Javascript的原型链中, 原型继承与标识符查找有些迷惑,

如, 如下的代码:

  1. function Foo() {};
  2. var foo = new Foo();
  3. Foo.prototype.label = “laruence”;
  4. alert(foo.label); //output: laruence
  5. alert(Foo.label);//output: undefined

今天看到了如下这个图:

Javascript object layout

另外, 在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. function Foo() {};
  2. var foo = new Foo();
  3. Foo.__proto__.label = “laruence”;
  4. alert(Foo.label); //output: laruence
  5. alert(foo.label);//output: undefined

而, 显然的:

  1. function Foo() {};
  2. alert(Foo.__proto__ === Foo.prototype); //output: false

另外, 也解释了,

  1. alert(Object.forEach); // undefined
  2. Function.prototype.forEach = function(object, block, context) {
  3.     for (var key in object) {
  4.         if (typeof this.prototype[key] == “undefined”) {
  5.             block.call(context, object[key], key, object);
  6.         }
  7.     }
  8. };
  9. alert(Object.forEach);
  10. alert(Function.forEach);
  11. alert(Object.forEach === Function.forEach); // true

转载请注明: 转载自—艾瑞可erik

本文链接地址: http://erik.xyz/616.html

标签:,

发表评论