我有以下代码,并且我试图从基类继承。为什么代码会说未定义identify()
?它不应该从基类中调用该函数吗?
错误:ReferenceError:标识未定义source1.js:23:9
class TestBase {
constructor() {
this.type = "TestBase";
}
run() {
console.log("TestBase Run");
}
identify() {
console.log("Identify:" + this.type);
}
}
class DerivedBase extends TestBase {
constructor() {
super();
this.type = "DerivedBase";
}
run() {
console.log("DerivedBase Run");
identify();
}
}
window.onload = function() {
let derived = new DerivedBase();
derived.run();
}
答案 0 :(得分:5)
在调用函数this
之前添加identify()
;
run() {
console.log("DerivedBase Run");
this.identify();
}
答案 1 :(得分:2)
答案 2 :(得分:0)
identify()是定义它的类的功能,因此,如果直接编写identify()
,它将查找window.identify()
,在我们的例子中是不正确的。因此,要定义当前范围以寻找identify()
函数,我们需要提及 this ,它将代表定义了i9t的当前类。
您的正确答案是
run() {
console.log("DerivedBase Run");
this.identify();
}
您改进后的代码如下:-
class TestBase {
constructor() {
this.type = "TestBase";
}
run() {
console.log("TestBase Run");
}
identify() {
console.log("Identify:" + this.type);
}
}
class DerivedBase extends TestBase {
constructor() {
super();
this.type = "DerivedBase";
}
run() {
console.log("DerivedBase Run");
this.identify();
}
}
/*window.onload = function() {
let derived = new DerivedBase();
derived.run();
}*/
let derived = new DerivedBase();
derived.run();