gpt4 book ai didi

javascript - Js,将静态函数从Class设置为变量对象时 'this'是什么

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:40:59 25 4
gpt4 key购买 nike

class Obj {
static log(){
console.log(this)
}
}

var test = Obj.log

Obj.log() // class Obj
test() // undefined

这是我运行的代码没有'use strict'。结果我不明白。为什么函数 test 记录 undefined 而不是全局对象?

最佳答案

这是因为 class 代码是always strict 代码。来自 the spec

NOTE     A class definition is always strict code.

因为 class 代码总是严格的,方法 log 是一个严格的函数(所以除其他外,它的内部 [[ThisMode]] 槽被设置为 strict),并且当你调用一个严格的函数而不设置 this 时,this 被设置为 undefined 用于调用。

规范中设置此操作的链是直接调用表达式 is evaluated通过最终调用规范的摘要 EvaluateDirectCall thisValue 设置为 undefined 的操作。这反过来调用 Call传递 thisValue,调用 [[Call]]在将 thisValue 作为 thisArgument 传递的函数上调用 OrdinaryCallBindThis ,它检查函数的 [[ThisMode]],如果它是 strict,则直接将 thisValue 设置为 thisArgument 而无需进一步的逻辑(而如果它不严格,它将用全局对象替换 nullundefined 并对任何其他值执行 ToObject。

关于javascript - Js,将静态函数从Class设置为变量对象时 'this'是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43013945/

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