2017-05-24 6 views
0

私はES6を初めて使用しており、継承を使用するためにコードをリファクタリングしていますが、わからないこのエラーに遭遇しました。JavaScript Es6クラス 'extends'が抽象クラスのメソッドを緩める

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 
+2

これは持って配列に追加するとき

誰かがこれを説明するのに役立つことができますしてください、子クラスは親クラスのメソッドにアクセスすることはできませんES6、クラス、または継承とは関係ありません。あなたのやり方で配列に追加されるメソッドは、独自のメソッドにもアクセスできません。 'console.log(this)'を試してみてください。 – Bergi

+0

@Bergiありがとう、それは私が良いことを理解するのを助けた。 – ajc

答えて

0

あなたはbindへの呼び出しを逃している:

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

ありがとうございました@Paulpro – ajc

関連する問題