gpt4 book ai didi

javascript - 奇怪的 $.each 行为

转载 作者:行者123 更新时间:2023-11-30 12:34:11 25 4
gpt4 key购买 nike

考虑以下示例:

var x = [1, 2, 3];
$.each(x, function(){
console.log(this);
});

var o1 = {x:1, y:2};
var o2 = {a:1, b:2};
var o3 = {d:1, e:2}
var y = [o1, o2, o3];
$.each(y, function(){
console.log(this);
});

这两个都按预期工作:this 引用传入的集合中当前引用的对象。

然而,下一个例子真的很奇怪。

var z = [null];
$.each(z, function(){
console.log(this);
});

在此示例中,您会注意到 window 已记录到控制台。

为什么会这样?

通过像这样进行更明确的参数化可以很容易地解决这个问题:

$.each(z, function(key, value){
console.log(value);
});

但我特别好奇为什么 this 在前面的例子中引用 window

最佳答案

看一看 $.each 的源代码,您就会明白这里发生了什么。

for (; i < length; i++) {
value = callback.call(obj[i], i, obj[i]);

if (value === false) {
break;
}
}

发件人:http://james.padolsey.com/jquery/#v=1.10.2&fn=jQuery.each

jQuery 正在使用 .call() 来触发您的回调函数。根据 Mozilla 的 .call 文档:

Note that this may not be the actual value seen by the method: if the method is a function in non-strict mode code, null and undefined will be replaced with the global object, and primitive values will be boxed.

发件人:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call

关于javascript - 奇怪的 $.each 行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26636771/

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