我在使用 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 变量的值)。
当鼠标离开each函数时,that.categoryId和categoryId有不同的值: 类别 ID = "abc" that.categoryId = "abc+"
我不明白以下内容:它们应该是分隔的变量,为什么它们以相同的值开头?
谢谢, 奥斯卡
编辑:抱歉,复制和粘贴时我忘记添加函数声明。它位于由“onclick”事件调用的函数内部。
最佳答案
如果您不在函数内部,则 varcategoryId = 'abc'
与 window.categoryId = 'abc'
具有相同的效果。
如果您不在函数内部,则 this
是 window
所以你看到的是预期的行为。
参见your js console for this live example
Edit: sorry, when coppying and pasting I forgot to add the function declaration. It is inside a function that is called by an "onclick" event.
关于javascript - 在每个函数内处理 "that"时出现奇怪的 JS 行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11937697/