The state of the bound parameter in the promise
I am interested in the time when I associate something with a promise.
var that = this;
function p(){
var promise = new Promise(
function (yes, no) {
/* .... */
/* .... */
}).then(function (val) {
/* .... */
/* .... */
}.bind(this));
}.bind(this)
Will there be a condition
that === this
allways returns true, given that the scope outside of the promise is asynchronous, and .then
may be resolved later in the lifecycle.
In other words, will it this
have the same meaning as when the first function was called, or will it have a meaning since it is actually used in the part .then
?
source to share
The value is this
determined by what is to the left of point in the calling method. If you don't call a method on the object, it this
will be global (window in the browser).
In your example, the line var that = this
sets the value of this to this global window variable (or global). Therefore, in this particular case, it will always equal this. However, this has a side effect if you used another object like this
and then in
function (yes, no) {
/* .... */
/* .... */
}
this !== that
I made a small fiddle as an example http://jsfiddle.net/metaf0x9/
source to share
Inside the function then
, that === this
. This is true because of the function bind
.
There is no way to define a value inside a promise function this
, but it won't that
.
The reason is that we do not know the context in which the function will be called. This function is not tied to that
, so we know it won't be an object this
. The object this
can be global, or it can be associated with something else through a call bind
or call
. In this case, it this
will be different.
source to share