gpt4 book ai didi

Javascript 对象函数作用域

转载 作者:行者123 更新时间:2023-11-30 13:37:15 25 4
gpt4 key购买 nike

假设我有一个类:

var asdf = new Class({
myFunction: function () {
//some stuff here
},
anotherFunction: function() {
globalObject.dosomethingandusecallback(
function() { // this is the callback
//how do I call myFunction() here? I can't seem to get it to work?
}
);
}
});

在我的回调函数定义中尝试调用 myFunction 时,我似乎遇到了一些范围界定问题。我在这里错过了什么?我认为它应该在此上下文中访问 myFunction?

谢谢!

最佳答案

this 关键字复制到回调函数外部的变量中,并在回调函数中使用该变量:

anotherFunction: function() {
var self = this;
globalObject.dosomethingandusecallback(
function() { // this is the callback
self.myFunction();
}
);
}

关于Javascript 对象函数作用域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4342929/

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