Sunday, May 12, 2024
191
rated 0 times [  197] [ 6]  / answers: 1 / hits: 31092  / 13 Years ago, thu, december 29, 2011, 12:00:00

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();

More From » ecmascript-6

 Answers
29

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.


[#88324] Tuesday, December 27, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
gerardob

Total Points: 571
Total Questions: 115
Total Answers: 96

Location: Cyprus
Member since Mon, Oct 24, 2022
2 Years ago
gerardob questions
Fri, Jan 22, 21, 00:00, 3 Years ago
Thu, Jan 14, 21, 00:00, 3 Years ago
Tue, Jan 28, 20, 00:00, 4 Years ago
;