Javascript This Function Context
Without use scrict
Consider the following codes:
function f1() {
return this;
}
console.log(f1()); Since the following code is not in strict mode, and because the value of this is not set by the call, this will default to the global object
// In a browser:
Window {...} // 'window' global object
// In Node:
Object [global] {...} // 'global' global objectsee more info in Javascript Global Object
With use strict
In strict mode, however, if the value of this is called directly (e.g. not set when entering an execution context), it remains as undefined
function f2() {
'use strict'; // enable strict mode
return this;
}
console.log(f2()); // outputs 'undefined' no matter in what environment Called as a method of an object
However, if f3 was called as a method or property of an object, then this would return the object a
function f3() {
'use strict';
return this;
}
// f3 was called as a method of an object
var a = { b: f3 };
console.log(a.b()); // { b: [Function: f2] }