我想将参数传递给在另一个函数中调用的函数dothis(param1, param2)
,我之前定义了函数dothis(param1,param2)
(这需要两个参数param1和param2),这不起作用:
function longfunctionfirst(param1,callback) {
setTimeout(function() {
dothis(param1,'param2');
if(typeof callback == 'function')
callback();
}, 3000);
};
function shortfunctionsecond() {
setTimeout('whatever();', 200);
};
longfunctionfirst(param1,shortfunctionsecond);
编辑:
var param1 = document.getElementsByTagName("a")[0];
function dothis(element,event) {
if (document.createEvent) {
// dispatch for firefox + others
var evt = document.createEvent("HTMLEvents");
evt.initEvent(event, true, true ); // event type,bubbling,cancelable
return !element.dispatchEvent(evt);
} else {
// dispatch for IE
var evt = document.createEventObject();
return element.dothis('on'+event,evt)
}
}
答案 0 :(得分:0)
要按原样传递参数,请使用arguments
和.apply()
function origin(a, b) {
nested.apply(this, arguments);
}
function nested (a, b) {
console.log(a, b);
}
origin('parameter1', 'parameter2');
答案 1 :(得分:0)
此代码不起作用,因为参数param1在setTimeout中的匿名函数范围内未定义。尝试传递param1 throw longfunctionfirst,如:
function longfunctionfirst(param1, callback) {
setTimeout(function() {
dothis(param1,'param2');
if(typeof callback == 'function')
callback();
}, 3000);
};
测试用例
function dothis(param1,param2){alert(param1);}
longfunctionfirst("xxx"); // alert with xxx will be displayed
答案 2 :(得分:0)
你的问题是范围相关的,setTimeout中的函数在longfunctionfirst范围之外执行,所以param1和callback不再是匿名函数的范围,请尝试这样:
function dothis(param1,param2){alert(param1);}
function whatever(){alert('Hello');}
function longfunctionclosure(param1, callback) {
return function() {
dothis(param1,'param2');
if(typeof callback == 'function')
callback();
}
}
function longfunctionfirst(param1,callback) {
setTimeout(longfunctionclosure(param1, callback), 3000);
};
function shortfunctionsecond() {
setTimeout('whatever();', 200);
};
longfunctionfirst('test',shortfunctionsecond);