代码之家  ›  专栏  ›  技术社区  ›  SinisterMJ

javascript:调用基类函数

  •  0
  • SinisterMJ  · 技术社区  · 6 年前

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

    错误:引用错误:未定义标识源1。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 回复  |  直到 6 年前
        1
  •  2
  •   falinsky Giri Dharan    6 年前

    你必须打电话 this.identify() 相反。

    有关更多信息,请阅读 classes 一般来说。

    请考虑到,javascript中的类只是一种在 prototypal inheritance .

        2
  •  5
  •   falinsky Giri Dharan    6 年前

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

    run() {
      console.log("DerivedBase Run");
      this.identify();
    }
    
        3
  •  0
  •   falinsky Giri Dharan    6 年前

    AS 识别() 是在其中定义它的类的函数,因此如果编写 identify() 然后它会直接寻找 window.identify() 在我们的情况下,这是不正确的。因此要定义当前范围以查找 识别() 功能,我们需要提到 ,表示当前定义了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();