在意想不到的结果在callback

以下代码是node.js的Javascript。 当我运行它,控制台打印undefined,我不知道为什么。 我希望它打印“托托”。 你能让我知道为什么我没有得到我的预期结果,但没有定义,我怎么能得到我的预期结果打印?

var Obj = function() {}; Obj.prototype.content = undefined; Obj.prototype.showContent = function() { console.log(this.content); } Obj.prototype.init = function(callback) { this.content = 'toto'; callback(); } var myObj = new Obj(); myObj.init(myObj.showContent); 

因为当你传递这样的函数的时候,就会失去this上下文。 您需要将该函数绑定到其父对象。

 myObj.init(myObj.showContent.bind(myObj)); 

你写它的方式, this里面的showContent将引用模块范围,而不是myObj

这是一个演示 。