测试代码:

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 方法。

 posted on 2012-01-30 18:10  落叶满长沙  阅读(351)  评论(0编辑  收藏  举报