调用带有promise和'this'上下文
Calling object methods with promises and the 'this' context
我知道在Javascript对象中,this
关键字不是通过声明定义的,而是通过调用定义的。所以我想知道我们如何才能避免以下问题:
var testObject = function(){
this.foo = "foo!";
};
testObject.prototype.sayFoo = function() {
console.log(this.foo);
};
var test = new testObject();
test.sayFoo(); //Prints "!foo"
new Promise(function(resolve, reject){
resolve();
}).then(test.sayFoo); //Unhandled rejection TypeError: Cannot read property 'foo' of undefined
:
new Promise(function(resolve, reject){
resolve();
}).then(function(){
test.sayFoo();
});
是唯一的解决方案吗?
不,您也可以使用bind
方法:
Promise.resolve().then(test.sayFoo.bind(test));
参见如何在回调中访问正确的' this '上下文?对于一般问题。
然而,Bluebird确实提供了一种额外的方法来调用该方法:
Promise.resolve().bind(test).then(test.sayFoo);
相关文章:
- Twitter Bootstrap typeahead:使用“this”获取上下文/调用元素
- extjs中事件处理程序函数中的THIS上下文
- 在对象文字的声明中继承上下文(this)?“自我”还好吗
- 是否可以绑定javascript函数,使其本地上下文与“this”相同
- 当作为脚本运行时.js Node中“this”的上下文是什么
- 变量“this”上下文在重新赋值变量后未更新
- 浏览器化模块中的“this”上下文
- Node.js:在模块作用域中使用“this”运算符的上下文是什么
- 使用“this”时,函数会丢失上下文 - Raphael JS
- JavaScript承诺:具有绑定的深度嵌套上下文(this)
- d3.js/CoffeeScript:访问mouseover中类和路径的执行上下文(this)
- Angular服务"this"正在更改窗口对象的上下文
- 传递一个原型's函数作为参数而不丢失'this'上下文
- 全局上下文和“this”;在node . js
- ' this '在全局上下文中和内部函数中
- 保留'this'上下文
- 在回调中调用Js `this`上下文
- JS bind(),我需要两个“this”上下文
- 我如何传递一个非'this'上下文到函数
- 调用带有promise和'this'上下文