正如 Nik020 指出的那样,您可以使用闭包。立即调用函数表达式 (IIFE) 创建一个闭包,但它不必是 IIFE 模式。一个普通的命名函数会做同样的事情
function main() {
var translation = 0;
function main() {
// load images
loopClosure(images);
}
function loopClosure(images) {
// setup webgl
function render() {
window.requestAnimationFrame(render);
// use translation here to update image locations
}
render();
}
document.addEventListener('keydown', keyboardHandler, false);
function keyboardHandler(event) {
if (event.key == 'ArrowLeft') {
translation--;
}
if (event.key == 'ArrowRight') {
translation++;
}
}
}
main();
IIFE 模式只是意味着您不必想出名称,并且名称不会与其他名称冲突。
您也可以绑定this。示例
class App {
constructor() {
this.translation = 0;
document.addEventListener('keydown', this.keyboardHandler.bind(this), false);
}
keyboardHandler(event) {
if (event.key == 'ArrowLeft') {
this.translation--;
}
if (event.key == 'ArrowRight') {
this.translation++;
}
}
}
const app = new App();
您使用箭头函数作为绑定this的语法糖
class App {
constructor() {
this.translation = 0;
document.addEventListener('keydown', (event) => {
if (event.key == 'ArrowLeft') {
this.translation--;
}
if (event.key == 'ArrowRight') {
this.translation++;
}
}, false);
}
}
const app = new App();
如果您希望能够移除监听器并且您正在使用箭头函数或绑定,您可以将函数引用存储在变量中
class App {
constructor() {
this.translation = 0;
const keyboardHandler = (event) => {
if (event.key == 'ArrowLeft') {
this.translation--;
}
if (event.key == 'ArrowRight') {
this.translation++;
}
};
document.addEventListener('keydown', keyboardHandler, false);
}
}
const app = new App();
bind this 和/或make a closure 还有 4 到 10 种方法。