javascript:调用基础class函数

javascript: call base class function

我有以下代码,我正在尝试从基础 class 继承。为什么代码说 identify() 未定义?它不应该从基础 class 调用函数吗?

Error: ReferenceError: identify is not defined 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();
}

您必须改为调用 this.identify()

有关详细信息,您可以阅读有关 classes 的一般信息。

请注意 javascript 中的 类 只是 prototypal inheritance 之上的语法糖。

在调用函数前添加this identify();

run() {
  console.log("DerivedBase Run");
  this.identify();
}

因为identify()是定义在class里面的函数,所以如果直接写identify()那么它会寻找window.identify() 这在我们的例子中是不正确的。所以要定义当前范围来寻找identify()函数,我们需要提到this,这将代表当前定义i9t的class。

您的正确答案是

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();