繁体   English   中英

处理每个函数内部的“那个”时的奇怪JS行为

[英]Strange JS behavior when handling “that” inside an each function

我在使用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”来访问它。

问题是:当执行首先进入每个方法时,输出that.categoryId将生成“abc”(我赋给本地categoryId变量的值)。

当鼠标离开每个函数时,that.categoryId和categoryId具有不同的值:categoryId =“abc”that.categoryId =“abc +”

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

谢谢,奥斯卡

编辑:对不起,当coppying和粘贴我忘了添加函数声明。 它位于由“onclick”事件调用的函数内部。

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

如果你不在函数内部,那么this就是window

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

有关此实例,请参阅js控制台

编辑:对不起,当coppying和粘贴我忘了添加函数声明。 它位于由“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). 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM