1. ホーム
  2. javascript

[解決済み] プロミスを使用すると、なぜクラスメソッド内で 'this' が未定義になるのですか?重複

2022-08-31 13:21:59

質問

javascriptのクラスがあり、それぞれのメソッドは Q プロミスを返します。私はなぜ this が未定義である理由を知りたい。 method2method3 . このコードにもっと正しい書き方があるのでしょうか?

function MyClass(opts){
  this.options = opts;

  return this.method1()
    .then(this.method2)
    .then(this.method3);
}

MyClass.prototype.method1 = function(){
  // ...q stuff...

  console.log(this.options); // logs "opts" object

  return deferred.promise;
};

MyClass.prototype.method2 = function(method1resolve){
  // ...q stuff...

  console.log(this); // logs undefined

  return deferred.promise;
};

MyClass.prototype.method3 = function(method2resolve){
  // ...q stuff...

  console.log(this); // logs undefined

  return deferred.promise;
};

これを解決するには bind :

function MyClass(opts){
  this.options = opts;

  return this.method1()
    .then(this.method2.bind(this))
    .then(this.method3.bind(this));
}

しかし、なぜ bind は必要なのでしょうか? .then() 殺す this を切る?

どのように解決するのですか?

this は常にメソッドが呼び出されたオブジェクトです。しかし、メソッドを渡すときに then() に渡した場合、あなたはそれを呼び出してはいないのです! メソッドはどこかに保存され、後でそこから呼び出されることになります。もしあなたが this を保存したい場合は、このようにする必要があります。

.then(() => this.method2())

を保存するか、ES6以前の方法で行う必要があります。 this を前にする必要があります。

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