首页 > 解决方案 > javascript:调用基类函数

问题描述

我有以下代码,我正在尝试从基类继承。为什么代码说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();
}

标签: javascriptclassecmascript-6extendsprototypal-inheritance

解决方案


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

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

推荐阅读