问题
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?
回答1:
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 let this
evaluate to undefined
when the function gets called without a context.
Relevant quotes from the spec:
1:
All parts of a ClassDeclaration or a ClassExpression are strict mode code
~ ES 262, 10.2.1 Strict Mode Code
2:
- If the function code for this MethodDefinition is strict mode code, let strict be true. Otherwise let strict be false.
[...]
Let closure be FunctionCreate(kind, UniqueFormalParameters, FunctionBody, scope, strict, prototype).
Perform MakeMethod(closure, object).
~ ES 262, 14.3.7 Runtime Semantics: DefineMethod
来源:https://stackoverflow.com/questions/56918107/using-a-class-method-in-the-global-context-has-this-as-undefined