gpt4 book ai didi

Javascript - 范围在回调中丢失

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:26:22 25 4
gpt4 key购买 nike

我有以下代码:

var myPage = {};
myPage.component = function(callback){

var somethingHappened = true;

if (somethingHappened){
callback();
}
};

myPage.main = function(){

// Initialise.
this.init = function(){

// make an instance of my component
this.component = new myPage.component( this.callback );

// need my utility function here
this.doSomethingUseful();
};

// Callback to be executed when something happs in the component.
this.callback = function(){
this.doSomethingUseful(); // doesn't work
};

// A useful utility that needs to be accessible from both the
// init() and callback() functions
this.doSomethingUseful = function(){
// some utility stuff
};
};
new myPage.main().init();

当从组件执行回调函数时,确保 myPage.main 作用域可用的最佳方法是什么?

最佳答案

使用bind :

this.callback = function(){
this.doSomethingUseful(); // doesn't work
}.bind(this);

关于Javascript - 范围在回调中丢失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13127468/

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