For each exercise try to guess the output. What this
points to, and more important, why? (Assuming the code is running in a browser).
Ex. #1:
function outer() {
const arrow = () => console.log(this);
arrow();
}
outer();
Ex. #2:
function outer() {
const obj = {
init: () => console.log(this)
};
obj.init();
}
outer();
Ex. #3:
const obj = {
nested: {
init: () => console.log(this)
}
};
obj.nested.init();
Ex. #4:
const object = {
init: function() {
(() => console.log(this))();
}
};
object.init();
Ex. #5:
const object = {
init: function() {
setTimeout(function() {
const arrow = () => console.log(this);
arrow();
}, 5000);
}
};
object.init();
Ex. #6:
const object = {
init: function() {
setTimeout(function() {
fetch("https://jsonplaceholder.typicode.com/todos/").then(function() {
const arrow = () => console.log(this);
arrow();
});
}, 5000);
}
};
object.init();
Ex. #7:
const object = {
init: function() {
setTimeout(function() {
const object = {
whoIsThis: function() {
console.log(this);
}
};
object.whoIsThis();
}, 5000);
}
};
object.init();
Put your solutions in the comments below!
Top comments (7)
That was a tough adventure. Couple of my answers were wrong for the first time.
After some thinking here are my solutions.
Two things to keep in mind:
this
)this
. Usually it's an object to the left of a dot.Ex 1
When a function is defined in global scope, it's defined in
window
object.outer()
is the same aswindow.outer()
, so the caller is window object.arrow
function have the samethis
asouter
, so the answer iswindow
.Ex 2
New execution contexts (including
this
) are created on function calls. Objects don't create new execution contexts, so the execution contexts stack here is the same as in Ex1, and the answer iswindow
.Ex 3
window
again!Ex 4
init
function is called byobject
, sothis
forinit
isobject
.Ex 5
This example is slightly harder than the previous one.
setTimeout
delays a callback execution. When it's time for the function to execute, who is the caller of this function? Right, it'swindow
object!Ex 6
Again, the anonymous function in
then
is executed bywindow
, and the answer iswindow
.Ex 7
This example can be simplified to
And based on the previous examples, it's clear that the answer is inner
object
.well done!
nice
Only be able to guess the first second and third one 😂 (I'm still learning JavaScript)
keep at it! :-)
Nice one sir, though everything seems 👽 to me here..lol
That's a good sign! :-)