【发布时间】:2012-09-04 09:21:20
【问题描述】:
由于当我们声明一个函数时,我们将其原型的构造函数属性指向函数本身,这样覆盖函数的原型是不是一种不好的做法:
function LolCat() {
}
// at this point LolCat.prototype.constructor === LolCat
LolCat.prototype = {
hello: function () {
alert('meow!');
}
// other method declarations go here as well
};
// But now LolCat.prototype.constructor no longer points to LolCat function itself
var cat = new LolCat();
cat.hello(); // alerts 'meow!', as expected
cat instanceof LolCat // returns true, as expected
我不是这样做的,我还是更喜欢下面的方法
LolCat.prototype.hello = function () { ... }
但我经常看到其他人这样做。
那么,为了方便起见,如第一个示例中那样,为了方便起见,通过覆盖函数的原型对象从原型中删除构造函数引用有什么影响或缺点吗?
【问题讨论】:
-
一个有趣的问题。我将在 Google 上闲逛一下,看看我能找到什么。
-
LolCat.prototype = { constructor: LolCat, ... } 使用它将保留构造函数。
标签: javascript constructor prototype