在不使用闭包的情况下,我们可以使用对象的属性来保存函数的上下文。例如:
function onClickHandler(event) { var button = event.target; var buttonInfo = button.getAttribute("data-info"); buttonInfoHandler.handleButtonClick(buttonInfo); }
var buttonInfoHandler = { lastButton: null, // 对象属性存储最后点击的按钮元素
handleButtonClick: function(buttonInfo) { if (this.lastButton !== null) { console.log("Last button clicked was: " + this.lastButton); } console.log("Current button clicked is: " + buttonInfo); this.lastButton = buttonInfo; } };
通过将onclick事件处理程序的上下文保存在对象的属性中,我们可以避免使用闭包来保存外部变量的引用。
下一篇:不使用闭包的替代解决方法