0

I am new to ES6 and am refactoring code to use inheritance but have come across this error that I do not understand.

Please can someone help explain this, the child class cannot access the parent class's methods when added to an array:

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
ajc
  • 3
  • 1
  • 2
    This has nothing to do with ES6, classes, or inheritance. A method that is added to an array in the way you did cannot even access "own" methods. Try `console.log(this)`. – Bergi May 24 '17 at 00:58

1 Answers1

0

You're missing a call to bind:

eventActions.push({test:tmp.method2_1.bind(tmp)});
Paul
  • 139,544
  • 27
  • 275
  • 264