I'm curious about the timing when I bind something to a promise.
var that = this;
function p(){
var promise = new Promise(
function (yes, no) {
/* .... */
/* .... */
}).then(function (val) {
/* .... */
/* .... */
}.bind(this));
}.bind(this)
Will the condition
that === this
allways return true, considering that the scope outside the promise is async and .then
might be resolved way later in the lifecycle.
In other words, will this
have the same value as when the first function was called, or will it have the value as it is actually used in the .then
part?
The value of this
is determined by what is to the left of the dot in the calling method. If you're not calling a method of an object, then this
will be the global (window in browser).
In your example the line var that = this
sets the value of that to that global variable window (or global). So in this specific case, this would always equal that. However that is due to a side effect, if you used a different object as this
, then in
function (yes, no) {
/* .... */
/* .... */
}
this !== that
I'm made a little fiddle as an example http://jsfiddle.net/metaf0x9/