gpt4 book ai didi

javascript - promise 和访问

转载 作者:行者123 更新时间:2023-11-28 19:10:55 25 4
gpt4 key购买 nike

我有两个功能:

p.test = 'test';

p.functionA = function(){

console.log('function A');
var dfd = new $.Deferred();

setInterval(function(){dfd.resolve();}, 2000);

return dfd.promise();

};


p.functionB = function(){

console.log('function B');
console.log(this.test);
var dfd = new $.Deferred();

setInterval(function(){dfd.resolve();}, 2000);

return dfd.promise();
};

函数的调用方式如下:

this.functionA().then(this.functionB);

我希望获取函数 B 中 test 的值,但它是未定义的。为什么?我怎样才能访问它?

最佳答案

您可以bind函数的上下文:

this.functionA().then( this.functionB.bind( this ) );

如果您想支持IE8并且不想使用bind polyfill ,您还可以使用jQuery's proxy :

this.functionA().then( $.proxy( this.functionB, this ) );

如果你不想一直重复这个,你也可以使用更完整的 Promise 库,比如 Bluebird 。您需要更新返回值以返回可信的 promise :

return Promise.resolve( dfd.promise() ).

然后你可以使用:

Promise.bind(this).then( this.functionA ).then( this.functionB ). ...

关于javascript - promise 和访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30733504/

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