Reputation: 49
I was learning this
in JavaScript and according to my understanding inside strict mode this
should be undefined but when I try this
"use strict";
function demo () {
// Here this is Undefined in strict mode
console.log(this);
}
//Here this refers to the Global Object
console.log(this);
demo();
As mentioned in the comment, console still prints the Window Object except when I call the demo() object. Why is that so?
Upvotes: 3
Views: 333
Reputation: 19344
ECMA2015 (ES6) specified that global environment records supply a this
value:
8.1.1.4.8 HasThisBinding () Global Environment Records always provide a this binding whose value is the associated global object.
By ECMA2018,this was modified slightly - from table 17 in section 8.1.1.4 Global Environment Records of this edition:
Table 17: Additional Fields of Global Environment Records
...
Field Name: [[GlobalThisValue]]
Value: Object
Meaning: Object The value returned bythis
in global scope. Hosts may provide any ECMAScript Object Value.
However typical host environments still set the global this
value to the global object and I assume will continue to do so.
While strict mode does provide that the this
value in an function called simply and directly to be undefined
, it does not suppress the creation of a binding for this
in the global environment record which will be seen as the this
value in global, file-level code.
Upvotes: 3