这是简单的脚本:
function parentFunc() {
var x = 15;
process(x);
}
parentFunc();
function process(x) {
alert(x);
}
现在当页面加载时,parentFunc()
正在执行,调用process()
函数以及向其发送参数;有什么办法可以做到这样吗?parentFunc()
被调用它只是将参数发送到process()
函数而不执行它?我需要一个没有全局变量的解决方案。
如果我正确理解你的问题,你想将某个参数绑定到process
并稍后执行该函数?
You can do this with .bind() [MDN] https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/bind. It accepts a context and arguments and creates a new function:
var process_bound = process.bind(null, x);
// later
process_bound();
对于不支持的浏览器的实现.bind()
,看看MDN文档(或者看Rocket的评论)。
以下是您应该如何使用它:
function process(x) {
alert(x);
}
function parentFunc() {
var x = 15;
return process.bind(null, x);
}
var process_bound = parentFunc();
// now bind the event handler to the element
var element = document.getElementById('someId');
element.onclick = function() {
process_bound();
return false;
};
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)