Skip to content

Instantly share code, notes, and snippets.

@sota1235
Last active August 11, 2016 06:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sota1235/41516f89ada98365c375c45eaea6dc2e to your computer and use it in GitHub Desktop.
Save sota1235/41516f89ada98365c375c45eaea6dc2e to your computer and use it in GitHub Desktop.
class Hoge {
constructor() {
this.text = 'text';
this.b = this.b.bind(this);
}
a() {
return new Promise(resolve => resolve(this.text));
}
b() {
console.log('b() this');
console.log(this);
return new Promise(resolve => resolve(this.text));
}
c() {
console.log('c() this');
console.log(this);
return new Promise(resolve => resolve('tmp'));
}
d() {
console.log('d() this');
console.log(this);
}
}
const hoge = new Hoge;
const log = text => console.log(`text: ${text}`);
hoge.a()
.then(result => log(result)) // 1回目のthis参照は大丈夫
.then(hoge.b)
.then(result => log(result)) // constructorでbindした関数のthis参照は大丈夫
.then(() => {
console.log('Promise this');
console.log(this); // 空っぽ
return 'tmp';
})
.then(hoge.c) // 関数を渡すとthis参照が死ぬ
.then(() => hoge.c()) // 無名関数でラップするとthis参照は大丈夫(arrow function)
.then(function () { return hoge.c(); }) // 無名関数でラップするとthis参照は大丈夫
.then(() => hoge.d()) // Promiseを返さない関数のthisは大丈夫
.catch(err => console.error(err));
/**
* 実行結果
text: text
b() this
Hoge { text: 'text', b: [Function: bound b] }
text: text
Promise this
{}
c() this
undefined
c() this
Hoge { text: 'text', b: [Function: bound b] }
c() this
Hoge { text: 'text', b: [Function: bound b] }
d() this
Hoge { text: 'text', b: [Function: bound b] }
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment