2016-02-27 63 views
3

我在学习NodeJS,并且遇到很大问题。脚本nodeJS出现此错误

使用ES6和执行与node --harmony

在我的构造this告诉我它Magic {}bar()它从我的功能。

我到处寻找,但我没有找到如何解决它。

#!/usr/local/bin/node --harmony 

class Test { 
    constructor() { 
     var tab = [] 
     tab.push(this.bar) 

     console.log(this) // Magic {} 
     tab[0]("hello") 
     // this.bar("world") 
    } 
    foo(str) { 
     return str 
    } 
    bar(str) { 
     console.log(this.foo(str)) // TypeError: this.foo is not a function 
     console.log(this) // [ [Function: bar] ] 
    } 
} 
new Test() 

回答

2

当你做tab.push(this.bar)时,它会丢失当前的上下文。你需要a)绑定它:tab.push(this.bar.bind(this))或者b)当调用时传递上下文:tab[0].call(this, "hello")

1

您必须在构造函数中绑定this

this.foo = this.foo.bind(this); 

在构造函数中

相关问题