【问题标题】:javascript: call base class functionjavascript:调用基类函数
【发布时间】:2018-07-24 14:12:39
【问题描述】:

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

【问题讨论】:

  • 你试过打电话给this.indentify()吗?
  • 是的,我做到了。没用。
  • @SinisterMJ this.identify() 绝对有效。 codepen.io/anon/pen/zLwbQp
  • 因为这是复制粘贴错误... indentify() 在他的代码中,我没有注意到错字...

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


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

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

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

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

    【讨论】:

    • 啊,成功了。谢谢!几分钟后会接受,还不让我。
    • @Kingsley 谈话具有误导性,因为 falinsky 编辑了他的答案。
    【解决方案3】:

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

    【讨论】:

      猜你喜欢
      • 2013-03-30
      • 1970-01-01
      • 1970-01-01
      • 2011-05-15
      • 2014-01-01
      • 1970-01-01
      • 2015-07-30
      • 2016-09-23
      • 2010-09-28
      相关资源
      最近更新 更多