【发布时间】:2012-06-11 12:12:07
【问题描述】:
我正在尝试实现原型继承,但我不理解它的行为。
考虑以下示例:
var config = {
writable: true,
enumerable: true,
configurable: true
};
var defineProperty = function( obj, name, value ) {
config.value = value;
Object.defineProperty( obj, name, config );
}
var man = Object.create( null );
defineProperty( man, 'sex', 'male' );
var yehuda = Object.create( man );
defineProperty( yehuda, 'firstName', 'Yehuda' );
defineProperty( yehuda, 'lastName', 'Katz' );
当我访问 yehuda.sex 时返回 male 这是正确的,但是当我尝试更新实际发生的值时,它是在 yehuda 上创建一个新属性 sex。
一种可能的解决方案是直接访问原型属性 (Object.getPrototypeOf(yehuda).sex = 'female'),但这意味着我需要知道对象所属的属性。
【问题讨论】:
-
你知道,
man.sex = 'male'就足够了 :-)
标签: javascript jquery inheritance prototype