Using a class method in the Global context has `th

2019-07-08 20:09发布

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条回答
Evening l夕情丶
2楼-- · 2019-07-08 20:36

All classes, 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:

  1. If the function code for this MethodDefinition is strict mode code, let strict be true. Otherwise let strict be false.

[...]

  1. Let closure be FunctionCreate(kind, UniqueFormalParameters, FunctionBody, scope, strict, prototype).

  2. Perform MakeMethod(closure, object).

~ ES 262, 14.3.7 Runtime Semantics: DefineMethod

查看更多
登录 后发表回答