I am facing difficulty understanding the below code.
function foo() {
console.log( this.a );
}
var obj = {
a: 2,
foo: foo
};
var a = 4;
obj.foo();
setTimeout( obj.foo, 100 );
setTimeout( obj.foo.bind(obj), 100 );
Its output comes as 2, 4, 2 which I am not able to understand.
“This” keyword refers to an object that is executing the current piece of code. It references the object that is executing the current function. If the function being referenced is a regular function, “this” references the global object.
In JavaScript, “this” variable is a variable that every execution context gets, in a regular function call. Every JavaScript function has a reference to its current execution context while executing, called this. Execution context means here means the manner of calling of functions.
In JavaScript, the this keyword refers to an object. Which object depends on how this is being invoked (used or called). The this keyword refers to different objects depending on how it is used: In an object method, this refers to the object. Alone, this refers to the global object.
Answers and Solutions Question: What is the output of 10+20+"30" in JavaScript? Answer: The output would be 3030. Javascript reads and evaluates from left to right, hence "+" acts as a concatenation operator when it encounters "30" (a string).
The first case,
obj.foo();
Where the this
inside of foo
will point obj
since you have assigned the function as a property of that particular object.
The second case,
setTimeout( obj.foo, 100 );
In setTimeout, the passed function will be eval
uated in the window's context. So here var a = 4;
was executed in window's context and became the property of window. when accessing this
inside the function foo
, that would point to window
at this particular situation.
The third case,
setTimeout( obj.foo.bind(obj), 100 );
You just bound the obj
as this
to the function foo
. And even though the function evaluated in window's context, the bound this
value won't be changed. That is the rule behind bind
function. So the this
won't be changed from obj
to window
here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With