gpt4 book ai didi

javascript - 如何正确处理回调堆栈

转载 作者:太空宇宙 更新时间:2023-11-04 02:30:54 25 4
gpt4 key购买 nike

我有一个看起来像这样的模块:

function MyMod(){}

MyMod.prototype.doSomething = function(handler){
//do stuff
var callback = function(){
//doStuff
handler();

};
anotherModule.doSomething(callback);
}


module.exports = MyMod

这工作正常,但我不想在我的 doSomething 方法中嵌入实际的回调方法,所以我尝试了以下方法:

    function MyMod(){}

MyMod.prototype.doSomething = function(handler){
this.handler = handler;
anotherModule.doSomething(this.someCallBack);
}

MyMod.prototype.someCallBack = function(){
//doStuff
this.handler();
}

module.exports = MyMod

这看起来更干净,更容易扩展,但这似乎不起作用。我似乎注意到,在执行这种方法时,他似乎丢失了对象的上下文,并且 this.handler 未定义。

如何在 Node.js 中正确处理这样的概念?

最佳答案

JavaScript 中的

this 指的是当前上下文。您可以使用 .apply.call 更改上下文,例如:

var fn = function() {  
console.log(this);
};
fn.call({}); // {}
fn.call([1,2,3]); // [1,2,3]

这意味着当将函数传递到其他模块等时,您必须关心 this 所指的内容:

var moduleA = { 
fn: function() {
// logic
this.fn2();
},
fn2: function() {
// more logic
}
};
var moduleB = {
fn: function(callback) {
// logic
callback();
}
};

moduleB.fn(moduleA.fn); // TypeError: undefined is not a function

发生这种情况是因为当调用moduleA.fn时,上下文(this)被设置为全局上下文:moduleA.fn -> fn -> fn(),为了防止这种情况,您可以使用.bind(context)

var fn = function() { console.log(this, arguments) };
var fnBound = fn.bind({});

fnBound(); // {};
fnBound.call([1,2,3]); // {} even works if people are trying to change the context

重点关注您的 2. 解决方案。

根据我们之前使用 moduleAmoduleB 进行的测试:

var moduleA = { 
fn: function() {
// logic
this.fn2();
},
fn2: function() {
// more logic
}
};
var moduleB = {
fn: function(callback) {
// logic
callback();
}
};

moduleB.fn(moduleA.fn.bind(moduleA)); // works

糖:

var fn = function() { console.log(this); };

// Bind context = {};
// Bind arguments[0] = 1
// Call with arguments = [2, 3]
// Final: context = {}, arguments = [1,2,3]
fn.bind({}, 1)(2, 3);

关于javascript - 如何正确处理回调堆栈,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26844761/

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