gpt4 book ai didi

javascript - 如何在 promise 的 then 回调中设置 `this` 的上下文

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:12:43 24 4
gpt4 key购买 nike

当我在 Promise 上调用 resolve() 时, then() 中的函数绑定(bind)到 window 的范围。

有任何方法可以像使用 Function.apply 一样设置 this 的上下文方法?

function Point(){
var that = this;

var _x = 0;

this.setX = function(x){
return new Promise((resolve, reject)=>{
setTimeout(()=>{
_x = x;
resolve.apply(that); //<== set this
}, 1000);
});
}

this.getX = function(){
return _x;
}
}

var p = new Point();
p.setX(10).then(function(){
console.log(this.getX()); //this === `window`
});

编辑:

详细说明,使用同步代码,您可以通过简单地一遍又一遍地返回相同的对象来进行方法链接。

//this pattern
obj.method1();
obj.method2();
...


//becomes this pattern
obj.method1(10).method2(11) ...

链接的实现

method1 = function(x){
return this;
}

当谈到异步时,你仍然可以用回调做同样的事情

obj.method1(10, function(){ this.method2(11, function(){ ...

回调实现

method1 = function(x, cb){
cb.apply(this);
}

我不明白为什么有人会将“receiver”函数绑定(bind)到窗口,这对我来说没有意义,因为 promises 应该类似于同步调用。

最佳答案

选项 1:

您可以将实例传递给解析函数。然后通过回调将其作为第一个参数引用。

function Point() {
var that = this;

var _x = 0;

this.setX = function(x) {
return new Promise((resolve, reject) => {
setTimeout(() => {
_x = x;
resolve(that); //<== set this
}, 1000);
});
}

this.getX = function() {
return _x;
}
}

var p = new Point();
p.setX(10).then(function(scope) {
console.log(scope.getX());
});

选项 2:

您可以绑定(bind)回调的范围:

var p = new Point();
p.setX(10).then(function () {
console.log(this.getX()); //this === `window`
}.bind(p)); // bind the scope here

function Point() {
var that = this;

var _x = 0;

this.setX = function(x) {
return new Promise((resolve, reject) => {
setTimeout(() => {
_x = x;
resolve.apply(that); //<== set this
}, 1000);
});
};

this.getX = function() {
return _x;
}
}

var p = new Point();
p.setX(10).then(function() {
console.log(this.getX()); //this === instance of Point
}.bind(p));

关于javascript - 如何在 promise 的 then 回调中设置 `this` 的上下文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41966403/

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