I have a class, which has a method that uses this
. I 'newed up' an instance of this object and passed on its method to a variable in the global context. If I then call my global function this
is undefined.
class Tests {
logThis() {
console.log(this);
}
}
const globalFunc = new Test().logThis;
globalFunc(); // undefined
Now, if I had just used an object literal then this
is is global.
const someObject= {
logThis2: function() {console.log(this)}
}
const globalFunc2 = someObject.logThis2;
globalFunc2(); // global object
In both cases the global object owns the code and should be supplying this
in the globalFunc
execution context. So why the difference in this
for a class generated method?
All
class
es, including their methods are evaluated in strict mode¹. Whenever a function gets created, and "its body is in strict mode"², then the function's internal [[mode]] property gets set to "strict". That will then letthis
evaluate toundefined
when the function gets called without a context.Relevant quotes from the spec:
1:
~ ES 262, 10.2.1 Strict Mode Code
2:
~ ES 262, 14.3.7 Runtime Semantics: DefineMethod