在JavaScript中,我如何访问超类的属性'实例?举个例子,我喜欢" prop"超级班级'实例设置为" true",但此代码创建并设置" prop"的子类'实例到" true",离开超类'实例" prop"为假:
var SuperClass = function() {
this.prop = true;
}
SuperClass.prototype.doStuff = function() {
if (this.prop) {
console.log('SuperClass does A.');
}
else {
console.log('SuperClass does B.');
}
}
SuperClass.prototype.load = function() {
this.prop = false;
}
SuperClass.prototype.setProp = function(val) {
this.prop = val;
}
function SubClass() {
SuperClass.call(this);
}
SubClass.prototype = Object.create(SuperClass.prototype);
SubClass.prototype.constructor = SubClass;
SubClass.prototype.doStuff = function() {
SuperClass.prototype.doStuff();
if (this.prop) {
console.log('SubClass does A.');
}
else {
console.log('SubClass does B.');
}
}
SubClass.prototype.load = function() {
SuperClass.prototype.load();
}
var anObject = new SubClass();
anObject.load();
anObject.setProp(true);
anObject.doStuff();
目前,输出是" SuperClass执行B. SubClass执行A。",这不是所需的结果。如何正确设置" prop"的值?所以他们都做了" A"?我并没有尝试在子类中创建一个新属性'例如,我想访问超类中的现有属性'实例
谢谢!
此外,您可以访问超类'来自子类的实例属性'构造函数?或者是否需要首先实例化子类?
答案 0 :(得分:5)
# maximum amount of time a message has to complete before it's considered failed
topology.message.timeout.secs: 30
你没有给超类赋予任何上下文,所以函数不会对当前对象起作用(即SubClass.prototype.doStuff = function() {
SuperClass.prototype.doStuff();
将是错误的。)
而是尝试:
this
这给了我想要的输出:
SubClass.prototype.doStuff = function() {
SuperClass.prototype.doStuff.call(this);