使用javascript super方法设置属性 [英] set attribute with javascript super method
问题描述
可能重复:
为什么我的JS对象属性被其他对象覆盖实例
在调用setT之后,为什么属性"t"没有更改?我希望输出为"4",但它会显示默认".
Why isn't the attribute "t" changed after setT was called? I would expect "4" as output, but it prints "default".
function Car(i) {
var id = i;
var t = "default";
this.getT = function() { return t; }
this.setT = function(p) {
t = p; // attribute t isn't changed ..
}
}
function ECar(id) {
Car.call(this, id); // super constructor call
this.setT = function(p) { // override
ECar.prototype.setT.call(this, p); // super call
}
}
ECar.prototype = new Car();
ecar = new ECar(3);
ecar.setT(4);
alert(ecar.getT()); // prints default, not 4
推荐答案
ECar.prototype = new Car();
在此行, ECar
的原型获得一个上下文,所有 ECar
的实例将在其中共享.
At this line ECar
's prototype get a context, in which all ECar
's instance will be shared.
ECar.prototype.setT.call(this,p);
此行将在那个上下文中调用,而不是在 Car.call(this,id);
上调用 super 时创建的内容
This line will call at that context, not what has been created while calling super at Car.call(this, id);
.
您可以使用以下方式修复代码
You can fix your code with
function ECar(id) {
Car.call(this, id); // super constructor call
var carSetT = this.setT;
this.setT = function(p) {
carSetT.call(this, p);
}
}
,但是使用真实的原型(例如
but it would be better (and more readable) to use real prototypes, such as
function Car() {}
Car.prototype.getT = function () { /* ... */ };
Car.prototype.setT = function () { /* ... */ };
function ECar() {}
ECar.prototype = new Car();
ECar.prototype.setT = function () { /* ... */ };
编辑: note (如@Bergi所建议)
Edit: note (as @Bergi suggested)
如果您必须支持旧版浏览器&,则应仅将 Child.prototype = new Parent()
用作继承.那么您应该只使用空的构造函数.
You should only use Child.prototype = new Parent()
as inheritance if you must support legacy browsers & then you should only use empty constructors.
JavaScript中用于继承的(其他语言)最兼容的方式是
The most (other-language) compatible way in JavaScript for inheritance is
Child.prototype = Object.create(Parent.prototype)
( MDN 说,它已被支持来自IE 9)
(MDN says it is supprted from IE 9)
这篇关于使用javascript super方法设置属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!