混淆javascript函数';s调用方法
我读了一篇关于的文章,我尝试复制它的代码,这可以提高循环速度:混淆javascript函数';s调用方法,javascript,function,call,Javascript,Function,Call,我读了一篇关于的文章,我尝试复制它的代码,这可以提高循环速度: var chunk = function (array, process, context) { setTimeout(function(){ var item = array.shift(); console.log('item', item);//this could show correctly process.call(item,
var chunk = function (array, process, context) {
setTimeout(function(){
var item = array.shift();
console.log('item', item);//this could show correctly
process.call(item, context);
if (array.length > 0){
setTimeout(arguments.callee, 100);
}
}, 100);
}
然后我尝试将参数传递给它,但我不知道如何使用上下文
参数,我所做的是:
var dosomething1 = function (item) {
console.log('this is begin ' + item)
}
var dosomething2 = function (item) {
console.log('this is end ' + item);
}
var process = function (item) {
console.log(item); //this show undefined
dosomething1(item);
dosomething2(item);
}
var temp = ["a", "b", "c", "d"];
chunk(temp, process);
问题在于处理函数中的开始,项
日志未定义
,该项只能在块中正确显示
那么我该如何解决这个问题呢?我认为它与进程.call
方法有关吗?它与上下文参数有关吗
您可以看到演示您将上下文作为第一个参数传递给call
,process.call(上下文,项)代码>。尽管您从未将上下文参数传递给块
,但这不是问题,因为您从未使用此
是的,你说得对。call方法是javascript中的继承概念,.call方法中的第一个参数用于将当前对象传递给其超类,第二个参数用作普通参数。试试这个
var chunk = function (array, process, context) {
setTimeout(function(){
var item = array.shift();
console.log('item', item);//this could show correctly
process.call(this, item);// the first parameter is the current object
if (array.length > 0){
setTimeout(arguments.callee, 100);
}
}, 100);
}
函数的call
方法使用指定的this
调用函数。传递函数的第一个参数(在本例中,调用process.call(item,context)
中的item
)将可通过函数中的this
关键字访问
因此,将此更改适当地引用:
var process = function () {
console.log(this);
dosomething1(this);
dosomething2(this);
}