测试代码:

function Dog(name) {
    this.name = name;
    Dog.prototype = {
        shout: function() { alert("I am " + this.name); }
    };
}
var dog1 = new Dog("Dog 1");
dog1.shout();

上面的代码看起来很“优美”,可一运行,却报错:“Object doesn’t support this property or method”.

对于代码:

Fn() {};
var fn = new Fn();

new Fn() 的实际构造过程可以等价为以下伪代码:

var o = {__proto__: Fn.prototype};
Fn.apply(o);
return o;

理解了 new 的构造过程,我们可以分析上面的实例了。

首先,JS引擎在遇到函数声明 function Dog(…) 时,会给函数对象添加 prototype 属性,伪代码如下:

Dog.prototype = {constructor: Dog};

当运行到 var dog1 = new Dog(”Dog 1″) 时,内部操作:

var o = {__proto__: Dog.prototype};
Dog.apply(o);
return o;

也许你已经知道问题所在了。为了更清楚,添加点注释:

// Dog.prototype = {constructor: Dog};
var o = {__proto__: Dog.prototype};
// 此时,o = {__proto__: {constructor: Dog}}
Dog.apply(o);
// 此时,Dog.prototype = {shout: function(){...}}
return o;

显然,运行 dog1.shout() 时,dog1 的确没有 shout 方法。

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2021-07-01
  • 2021-12-10
  • 2021-12-06
  • 2022-03-09
  • 2022-12-23
猜你喜欢
  • 2021-06-02
  • 2021-06-02
  • 2021-11-29
  • 2021-06-24
  • 2021-07-22
  • 2021-06-30
  • 2021-06-09
相关资源
相似解决方案