gpt4 book ai didi

javascript - 在全局上下文中使用类方法具有 `this` 未定义

转载 作者:行者123 更新时间:2023-11-29 20:35:10 25 4
gpt4 key购买 nike

我有一个类,它有一个使用 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 会有所不同呢?

最佳答案

所有 classes,包括它们的方法都在严格模式下评估¹。每当创建一个函数,并且“它的主体处于严格模式”²时,该函数的内部 [[mode]] 属性就会设置为“严格”。当函数在没有上下文的情况下被调用时,这将使 this 评估为 undefined


规范中的相关引述:

1:

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

~ ES 262, 10.2.1 严格模式代码


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 运行时语义:DefineMethod

关于javascript - 在全局上下文中使用类方法具有 `this` 未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56918107/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com