【发布时间】:2011-07-30 17:35:58
【问题描述】:
有人可以向我解释Me.prototype.constructor = Me; 的用法以及为什么需要此代码,什么时候可以正常工作而没有它?
在代码中,原型对象是在 Me 对象上创建的,它被实例化并替换旧的原型对象。为什么我需要在给定的代码中指向 Me 构造函数?
function Me(){
this.name = 'Dejan';
}
function You(){
this.name = 'Ivan';
}
Me.prototype = new You();
somebody = new Me();
Me.prototype.constructor = Me; // Why?
Me.prototype.foo = function(){
alert('Proto Me!'); // It always fire up this alert, ether constructor is pointing to Me or not... !
}
You.prototype.foo = function(){
alert('Proto You!');
}
somebody.foo();
alert(somebody.name); // Alert 'Dejan'
【问题讨论】:
-
我相信旧版浏览器会检查
.constructor属性中的instanceof关键字。
标签: javascript oop