Reputation: 550
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
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:
a()
this
will be either the global object or undefined
if running in strict mode.
obj.a()
this
will be set to the object, obj
in this case.
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()
var m = obj.a.bind(obj)
m();
this
will be set to the object passed as the first argument to .bind()
Upvotes: 3