【问题标题】:JavaScript Es6 Class 'extends' looses abstract class methods [duplicate]JavaScript Es6类“扩展”失去了抽象类方法[重复]
【发布时间】:2017-05-24 00:55:18
【问题描述】:

我是 ES6 新手,我正在重构代码以使用继承,但遇到了这个我不明白的错误。

请有人帮忙解释一下,子类在添加到数组时无法访问父类的方法:

class abstract1 {
    constructor(){
    }

    method1_2(){
        console.log('method1_2');
    }

    method1_1(){
        console.log('method1_1');
        this.method1_2();
    }
}

class test extends abstract1{
    constructor(){
        super();
    }

    method2_1(){
        console.log('method2_1');
        this.method1_1();
    }
}
let tmp = new test();
tmp.method2_1();

//All good with world, result:
// method2_1
// method1_1
// method1_2

console.log('Now Run from a callback');
let eventActions = [];
eventActions.push({test:tmp.method2_1});
eventActions[0].test();

//Not good with world:
// method2_1
// Uncaught TypeError: this.method1_1 is not a function
//    at Object.method2_1 [as test] (<anonymous>:22:8)
//    at <anonymous>:35:17

【问题讨论】:

  • 这与 ES6、类或继承无关。以您所做的方式添加到数组的方法甚至无法访问“自己的”方法。试试console.log(this)
  • 谢谢@Bergi,这帮助我更好地理解了事情。

标签: javascript class ecmascript-6 extends


【解决方案1】:

你错过了给bind的电话:

eventActions.push({test:tmp.method2_1.bind(tmp)});

【讨论】:

  • 谢谢@Paulpro
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-09-16
  • 2018-02-24
  • 1970-01-01
  • 2016-08-26
  • 1970-01-01
  • 2017-04-17
相关资源
最近更新 更多