Javascript 更改$.each()中的上下文
我正在尝试更改jQuery的Javascript 更改$.each()中的上下文,javascript,jquery,Javascript,Jquery,我正在尝试更改jQuery的$的上下文。每个方法。我错过了什么 $.each.call(this, [1,2,3], function(){ console.log(this); // expecting to see the window object }); var foo = { bar: 1 }; $.each.call(foo, [1,2,3], function(){ console.log(this); // expecting to see the foo ob
$的上下文。每个方法。我错过了什么
$.each.call(this, [1,2,3], function(){
console.log(this); // expecting to see the window object
});
var foo = { bar: 1 };
$.each.call(foo, [1,2,3], function(){
console.log(this); // expecting to see the foo object
});
有几种方法可以做到这一点
1) 从外部的参考窗口
var self = this;
$.each.call(this, [1,2,3], function(){
console.log(self); // expecting to see the window object
});
2) 将函数绑定到特定范围
$.each.call(this, [1,2,3], function(){
console.log(this); // expecting to see the window object
}.bind(this));
3) 使用绑定到当前上下文的ES6 arrow函数(如果没有一些6->5转换,在大多数浏览器中无法使用)
4) 直接引用窗口即可
$.each.call(this, [1,2,3], () => {
console.log(window); // expecting to see the window object
});
只需在回调上使用Function.bind
,即可指定要在哪个上下文中运行函数
$.each([1,2,3], (function(){
console.log(this); // expecting to see the window object
}).bind(this));
jQuery内部使用ThisBinding
修饰符,如apply
,call
。因此,此
将始终是一个数字,除非您指定要运行的回调的上下文。$。每个
在内部使用调用
和应用
在回调中设置正确的此
值,类似于回调.apply(obj[i])
,因此,它将数组用于这个
值,使用调用
调用该方法不会改变这一点
它是这样工作的
function each(obj, callback, args) {
var value, i = 0,
length = obj.length,
isArray = isArraylike(obj);
if (args) {
if (isArray) {
for (; i < length; i++) {
value = callback.apply(obj[i], args);
}
} else {
for (i in obj) {
value = callback.apply(obj[i], args);
}
}
}
return obj;
}
这个
永远是一个数字。谢谢,这正是我想知道的完整答案!只是缺少了旧浏览器支持的jQuery方式:$.each([1,2,3],$.proxy(function(){console.log(this);//希望看到窗口对象},this))代码>
function each(obj, callback, args) {
var value, i = 0,
length = obj.length,
isArray = isArraylike(obj);
if (args) {
if (isArray) {
for (; i < length; i++) {
value = callback.apply(obj[i], args);
}
} else {
for (i in obj) {
value = callback.apply(obj[i], args);
}
}
}
return obj;
}
var self = this;
$.each(arr, function() {
console.log( self );
});