【发布时间】:2011-12-26 22:36:39
【问题描述】:
考虑下面的代码。
function a() {}
function b() {}
function c() {}
b.prototype = new a();
c.prototype = new b();
console.log((new a()).constructor); //a()
console.log((new b()).constructor); //a()
console.log((new c()).constructor); //a()
- 为什么没有为 b 和 c 更新构造函数?
- 我是不是继承错了?
- 更新构造函数的最佳方法是什么?
此外,请考虑以下事项。
console.log(new a() instanceof a); //true
console.log(new b() instanceof b); //true
console.log(new c() instanceof c); //true
- 假设
(new c()).constructor等于a()并且Object.getPrototypeOf(new c())等于a{ },那么instanceof怎么可能知道new c()是c的一个实例?
【问题讨论】:
-
有什么理由需要更新构造函数?如果我只是假装财产不存在,我会发现我的生活会更轻松。
-
我很难将其作为副本关闭 - 所有其他 questinos 都如此冗长......
-
c.prototype是b()和b.prototype是a(),因此c.prototype是a() -
@pimvdb 是对的,需要手动设置构造函数。为了子孙后代 - 这是一个基于 Stoyan Stefanovs “Javacript Patterns”的伪经典继承模式的小提琴:jsfiddle.net/sunwukung/YXxG6
-
这是一个有用的小提琴,但你的
Child.hasOwnProperty('name')有点模棱两可 - 它返回true因为函数总是有一个.name属性(在这种情况下,"Child")。我不确定这是否是您的意思(不是Parent设置的name,因为构造函数没有设置该属性)。
标签: javascript inheritance constructor instanceof