我有一个类,它有一个使用 this
的方法。我“更新”了该对象的一个实例,并将其方法传递给全局上下文中的变量。如果我随后调用全局函数 this
则未定义。
class Tests {
logThis() {
console.log(this);
}
}
const globalFunc = new Test().logThis;
globalFunc(); // undefined
现在,如果我刚刚使用了对象文字,那么 this
就是全局的。
const someObject= {
logThis2: function() {console.log(this)}
}
const globalFunc2 = someObject.logThis2;
globalFunc2(); // global object
在这两种情况下,全局对象都拥有代码,并且应该在 globalFunc
执行上下文中提供 this
。那么为什么类生成方法的 this
存在差异呢?
最佳答案
所有类
,包括它们的方法,都以严格模式进行评估。每当创建一个函数并且“其主体处于严格模式”²时,该函数的内部 [[mode]] 属性就会设置为“strict”。当函数在没有上下文的情况下被调用时,这将使 this
计算为 undefined
。
规范中的相关引用:
1:
All parts of a ClassDeclaration or a ClassExpression are strict mode code
~ ES 262,10.2.1 严格模式代码
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 运行时语义:DefineMethod
关于javascript - 在全局上下文中使用类方法时, `this` 为未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56918107/