为什么this在Promise不起作用

原因 By Joseph see https://stackoverflow.com/questions/34930771/why-is-this-undefined-inside-class-method-when-using-promises

Promise handlers are called in the context of the global object (window) by default. When in strict mode (use strict;), the context is undefined. This is what's happening to method2 and method3.

;(function(){
  'use strict'
  Promise.resolve('foo').then(function(){console.log(this)}); // undefined
}());

;(function(){
  Promise.resolve('foo').then(function(){console.log(this)}); // window
}());

解决方法 By lex82 see https://stackoverflow.com/questions/34930771/why-is-this-undefined-inside-class-method-when-using-promises

this is always the object the method is called on. However, when passing the method to then(), you are not calling it! The method will be stored somewhere and called from there later. If you want to preserve this, you will have to do it like this:

.then(() => this.method2())
or if you have to do it the pre-ES6 way, you need to preserve this before:

var that = this;
// ...
.then(function() { that.method2() })

posted @ 2020-10-30 22:54  Bravo_Jack  阅读(306)  评论(0编辑  收藏  举报