在全局上下文中使用类方法具有未定义的“ this” [英] Using a class method in the Global context has `this` as undefined

查看:65
本文介绍了在全局上下文中使用类方法具有未定义的“ this”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类,该类具有使用 this 的方法。我新建了该对象的实例,并将其方法传递给全局上下文中的变量。如果然后我调用全局函数,则此是未定义的。

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

现在,如果我刚刚使用对象文字,那么 this 是全局的。

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

在两种情况下,全局对象均拥有代码,应提供 this globalFunc 执行上下文中。那么,为什么类生成的方法 this 的区别呢?

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?

推荐答案

所有,包括它们的方法,都以严格模式进行评估¹。每当创建函数并且其主体处于严格模式 2时,函数的内部[[mode]]属性就会设置为 strict。这样,当在没有上下文的情况下调用函数时,的评估结果为未定义

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.

规范中的相关报价:

1:


全部ClassDeclaration或ClassExpression的一部分是严格模式代码

All parts of a ClassDeclaration or a ClassExpression are strict mode code

〜ES 262,10.2.1严格模式代码

~ ES 262, 10.2.1 Strict Mode Code

2:



  1. 如果此MethodDefinition的功能代码严格模式代码,请严格执行。否则,请让严格为假。

[...]


  1. 让闭包成为FunctionCreate(种类,UniqueFormalParameters,FunctionBody,范围,严格,原型)。

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

执行MakeMethod(闭包,对象)。

Perform MakeMethod(closure, object).


〜ES 262,14.3.7运行时语义:DefineMethod

~ ES 262, 14.3.7 Runtime Semantics: DefineMethod

这篇关于在全局上下文中使用类方法具有未定义的“ this”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆