Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"this" context output not able to understand

Tags:

javascript

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.

like image 846
rosinghal Avatar asked Dec 26 '16 07:12

rosinghal


People also ask

What does the this function do?

“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.

What is this variable?

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.

What does the this keyword indicate in JavaScript?

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.

What is the output of 10 20 30 in JavaScript?

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).


1 Answers

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 evaluated 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.

like image 171
Rajaprabhu Aravindasamy Avatar answered Sep 30 '22 02:09

Rajaprabhu Aravindasamy