JavaScript原型和继承 - a special example by jfo

function A() {
A.prototype = {
print: function(){
alert(“print”);
}
};
}
var a = new A();
a.print(); // will cause exception: Object #<A> has no method ‘print’
a = new A(); // new second time
a.print(); // ok now

 

A本身是一个普通对象:

 

第一次new A() 的时候,先申请一片内存空间,赋予变量a,并将a的[[Prototype]]指向A.prototype(此时还没有print函数)

然后执行constructor,即A函数体,并将A的prototype重设(此时print函数设置完成)

 

这样第二次new A() 的时候,a的[[Prototype]]指向我们自己设置的那个prototype对象,就可以调用print函数了

 

 

参考:JavaScript原型和继承