这是我的代码:
function A()
{
this.prop = "A";
this.propName = this.getProp() + 'name';
}
A.prototype.getProp = function(){return this.prop;}
A.prototype.getPropName = function(){return this.propName;}
function B()
{
this.prop = "B";
}
B.prototype = new A();
var b = new B();
console.log(b.getPropName());
输出结果为:
Aname
但我希望这个:
Bname
我做错了什么?
修改
谢谢,我明白了。B从来没有一个名为'propName'的ownProperty,因此它使用A中的'propName',它在'new A'中初始化,之后它永远不会改变。
我可以通过以下方式修复它:
redefine the getter to function(){return this.prop + 'name';}
re-initilize in B
later initilize, keep the propName field, but default to null, the getter become to
function(){return this.propName||(this.propName = this.prop + 'name')}
我想使用最后一个。
再次感谢你。