javascript:调用基类函数

时间:2018-07-24 14:12:39

标签: javascript class ecmascript-6 extends prototypal-inheritance

我有以下代码,并且我试图从基类继承。为什么代码会说未定义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();
}

3 个答案:

答案 0 :(得分:5)

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

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

答案 1 :(得分:2)

您必须改为致电this.identify()

有关更多信息,您可以大致了解classes

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

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