Using a class method in the Global context has `this` as undefined

人走茶凉 提交于 2019-12-11 03:08:12

问题


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 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



来源:https://stackoverflow.com/questions/56918107/using-a-class-method-in-the-global-context-has-this-as-undefined

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!