Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/413.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
javascript:调用基类函数_Javascript_Class_Ecmascript 6_Extends_Prototypal Inheritance - Fatal编程技术网

javascript:调用基类函数

javascript:调用基类函数,javascript,class,ecmascript-6,extends,prototypal-inheritance,Javascript,Class,Ecmascript 6,Extends,Prototypal Inheritance,我有下面的代码,我试图从基类继承。为什么代码中说没有定义identify()?它不应该从基类调用函数吗 错误:ReferenceError:未定义标识source1.js:23:9 您必须调用this.identify() 有关更多信息,您可以阅读一般信息 请考虑到javascript中的类只是一个语法糖。在调用函数identify()之前添加this 由于identify()是定义它的类的函数,因此如果您直接编写identify(),它将查找window.identify(),在我们的例子中,

我有下面的代码,我试图从基类继承。为什么代码中说没有定义
identify()
?它不应该从基类调用函数吗

错误:ReferenceError:未定义标识source1.js:23:9


您必须调用this.identify()

有关更多信息,您可以阅读一般信息


请考虑到javascript中的类只是一个语法糖。

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

由于identify()是定义它的类的函数,因此如果您直接编写
identify()
,它将查找
window.identify()
,在我们的例子中,这是不正确的。因此,要定义当前作用域以查找
identify()
函数,我们需要提到this,它将表示定义i9t的当前类

你的正确答案是

改进后的代码如下:-

类TestBase{ 构造函数(){ this.type=“TestBase”; } 运行(){ log(“TestBase运行”); } 识别(){ console.log(“标识:“+this.type”); } } 类DerivedBase扩展了TestBase{ 构造函数(){ 超级(); this.type=“DerivedBase”; } 运行(){ 日志(“DerivedBase运行”); 这个。标识(); } } /*window.onload=函数(){ 让派生=新的DerivedBase(); 派生的。run(); }*/ 让派生=新的DerivedBase();
派生的。run()吗?是的。不起作用。@SinisterMJ
this.identify()
绝对起作用。因为这是一个复制粘贴错误。。。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");
        identify();
    }
}

window.onload = function() {
  let derived = new DerivedBase();
  derived.run();
}
run() {
  console.log("DerivedBase Run");
  this.identify();
}
run() {
  console.log("DerivedBase Run");
  this.identify();
}