Can anybody explain to me why A
is true and B
is false? I would have expected B to be true as well.
function MyObject() {
};
MyObject.prototype.test = function () {
console.log("A", this instanceof MyObject);
(function () {
console.log("B", this instanceof MyObject);
}());
}
new MyObject().test();
update: since ecmascript-6 you can use arrow functions which would make it easy to refer to MyObject like this:
function MyObject() {
};
MyObject.prototype.test = function () {
console.log("A", this instanceof MyObject);
(() => {//a change is here, which will have the effect of the next line resulting in true
console.log("B", this instanceof MyObject);
})(); //and here is a change
}
new MyObject().test();
this
is special. It refers to the object that the function is being called on behalf of (most commonly via dot syntax).
So, in the case of A
, the function is being called on behalf of a new MyObject
object. B
is in a different function that isn't explicitly being called on behalf of any object, so this
defaults to the global object (window
).
In other words, this
changes depending on how the function is called, not where or how it is defined. The fact that you're using an anonymous function (defined inside another function) is coincidental and has no effect on the value of this
.