在每个函数中处理“that”时奇怪的JS行为

Strange JS behavior when handling "that" inside an each function

本文关键字:行为 JS that 函数 处理      更新时间:2023-09-26

我注意到使用 javascript 进行开发时有一种不寻常的行为,有人可以向我解释一下吗?

我有一个javascript代码:

function MyFunction(){
   var categoryId = 'abc';
   var that = this;
   $(_elem).parent().find('[data-id]').each(function(){
   that.categoryId += $(this).data('id') + ',';
   });
   setEventsCategoryEx(categoryId, url, parentUrl);
}

应该是错误的,因为 categoryId 不是全局的,所以不应该使用 "that.categoryId" 访问它。

问题是:当执行首次进入 each 方法时,输出that.categoryId 将生成 "abc"(我分配给本地 categoryId 变量的值)。

当鼠标离开每个函数时,那个.categoryId和categoryId有不同的值:类别 ID = "abc"that.categoryId = "abc+"

我不明白以下内容:它们应该是分离的变量,为什么它们以相同的值开头?

谢谢奥斯卡

编辑:抱歉,在复制和粘贴时,我忘记添加函数声明。它位于由"onclick"事件调用的函数内。

如果您不在函数内,则var categoryId = 'abc'具有与window.categoryId = 'abc'相同的效果。

如果您不在函数内,则this window

所以你看到的是预期的行为。

有关此实时示例,请参阅您的 js 控制台

编辑:抱歉,在复制和粘贴时,我忘记添加函数声明。它位于由"onclick"事件调用的函数内。

编辑后,我无法重现该问题。

在非严格模式下调用未用作方法的函数时,this 是全局对象。

语言规范的第 11.2.3 节说:

生产 CallExpression : MemberExpression *Arguments* 的计算方法如下:

6. If Type(ref) is Reference, then
     If IsPropertyReference(ref) is true, then
       Let thisValue be GetBase(ref).
   Else, the base of ref is an Environment Record
     Let thisValue be the result of calling the ImplicitThisValue concrete method of GetBase(ref).