Amauri
Amauri

Reputation: 550

Behavior of this in Node environment

function a() {
return this;
}

function b() {
return this;
}

console.log(a() === b()) //true on browser and node 

But then...

function a() {
return "inside a";
}

function b() {
console.log(this.a()); //logs undefined on node, 'inside a' on browser
}

This is ran non-strict mode for both browser and node.

Upvotes: 2

Views: 49

Answers (1)

jfriend00
jfriend00

Reputation: 707326

The value of this is determined by how a function is called. It has little to do with how a function is defined.

If you call a function as just a plain function like

a()

Then, the value of this inside of the function a will be either the global object or undefined if running in strict mode.

Here are the ways the this can be controlled:

Plain Function call

a()

this will be either the global object or undefined if running in strict mode.

Method Call

obj.a()

this will be set to the object, obj in this case.

.apply() or .call()

obj.a.call(obj, arg1, arg2)
obj.a.apply(obj, array)

this will be set to the object passed as the first argument to .call() or .apply()

.bind()

var m = obj.a.bind(obj)
m();

this will be set to the object passed as the first argument to .bind()

Upvotes: 3

Related Questions