gpt4 book ai didi

回调中的javascript意外结果

转载 作者:行者123 更新时间:2023-11-30 16:49:54 24 4
gpt4 key购买 nike

以下代码是 node.js 的 Javascript。当我运行它时,控制台打印未定义,我不知道为什么。我预计它会打印“toto”。你能告诉我为什么我没有得到我的预期结果但未定义吗?我怎样才能打印出我的预期结果?

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 上下文。您需要将函数绑定(bind)到它的父对象。

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

按照您编写的方式,showContent 中的 this 将引用模块范围而不是 myObj

这是一个 demo .

关于回调中的javascript意外结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30685395/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com