【发布时间】:2011-09-12 15:50:39
【问题描述】:
我的理解是,如果对象具有给定成员而不检查原型链,则“hasOwnProperty”返回true。但是当我从其他对象继承时,我会看到最后一个对象本身的所有成员。
考虑以下示例:
var Object1 = function (param) {
this.prop1 = "p1 " + param;
this.prop2 = "p2 " + param;
};
var Object2 = function (param) {
Object1.apply(this, arguments);
this.prop3 = 'p3' + param;
};
Object2.prototype = new Object1();
var b = new Object2('this is Object 2');
for (var v in b)
print(v + ": " + b[v] + (b.hasOwnProperty(v)?' (own)':' (inherited)'));
此代码打印:
--prop1: p1 this is Object 2 (own)
--prop2: p2 this is Object 2 (own)
--prop3: p3this is Object 2 (own)
如果我看一下我看到的调试器:
b
Object2
prop1: "p1 this is Object 2"
prop2: "p2 this is Object 2"
prop3: "p3this is Object 2"
__proto__: Object1
但是,我删除了apply 行,一切都更有意义了,但是基础对象没有初始化:
--prop3: p3this is Object 2 (own)
--prop1: p1 undefined (inherited)
--prop2: p2 undefined (inherited)
现在我在调试器中看到:
b
Object2
prop3: "p3this is Object 2"
__proto__: Object1
prop1: "p1 undefined"
prop2: "p2 undefined"
__proto__: Object
据我所知,apply 就像......执行超类构造函数,因此超成员被正确初始化,但显然这会改变子对象的形状。
为什么会这样?在 JS 中继承的正确方法是什么——或者至少不那么混乱?
我正在查看一些有关它的信息,显然每个开发人员对如何做都有不同的感受。
问候。
【问题讨论】:
-
@John Hartsock 实际上不是,这个“问题”也发生在该线程的示例中。
标签: javascript oop inheritance prototypal-inheritance