向回调方法传递参数
通常下,你并不能给回调函数传递参数。 比如:
function callback() {
console.log('Hi human');
}
document.getElementById('someelem').addEventListener('click', callback);
你可以借助Javascript闭包的优势来传递参数给回调函数。看这个例子:
function callback(a, b) {
return function() {
console.log('sum = ', (a+b));
}
}
var x = 1, y = 2;
document.getElementById('someelem').addEventListener('click', callback(x, y));
什么是闭包? 闭包是指函数有自由独立的变量。换句话说,定义在闭包中的函数可以“记忆”它创建时候的环境。想了解更多请参考MDN的文档。
这种方法使参数x
和y
在回调方法被调用时处于其作用域内。
另一个办法是使用bind
方法。比如:
var alertText = function(text) {
alert(text);
};
document.getElementById('someelem').addEventListener('click', alertText.bind(this, 'hello'));
两种方法之间有着微小的性能差异,请看jsperf.
MEET THE NEW JSTIPS BOOK
You no longer need 10+ years of experience to get your dream job.
Use the 100 answers in this short book to boost your confidence and skills to ace the interviews at your favorite companies like Twitter, Google and Netflix.
GET THE BOOK NOW
MEET THE NEW JSTIPS BOOK
The book to ace the JavaScript Interview.
A short book with 100 answers designed to boost your knowledge and help you ace the technical interview within a few days.
GET THE BOOK NOW