假设我声明了一个函数并将其用作对象上事件的处理程序。
让我们说它需要访问一个变量,该变量的值会在调用事件之前发生变化。
如何在声明函数时向函数提供变量的值?
例如:
var I_Like_to_Change_Frequently = "...";
some_DOM_object.addEventListener( "some_arbitrary_event_to_fire_later", function I_Need_the_Current_Value(){
alert( "at the time I was defined, 'I_Like_to_Change_Frequently' was " + I_Like_to_Change_Frequently)
})
var I_Like_to_Change_Frequently = undefined //doesn't really matter. The point is it changes
编辑:此代码块在for循环中重复多次,其中some_DOM_object在每次迭代时都不同。每次迭代I_Like_to_Change_Frequently也都会改变。
答案 0 :(得分:0)
几个选项:
1)将代码移动到一个函数中。函数参数将是一个新的绑定,因此将被锁定在"到那个值
function createListener(domObject, val) {
domObject.addEventListener("some_arbitrary_event_to_fire_later", function () {
alert("at the time i was defined, I_Like_to_Change_Frequently was " + val;
});
}
var I_Like_to_Change_Frequently = "...";
createListener(some_DOM_object, I_Like_to_Change_Frequently);
var I_Like_to_Change_Frequently = undefined
2)与IIFE
内联var I_Like_to_Change_Frequently = "...";
(function (val) {
some_DOM_object.addEventListener( "some_arbitrary_event_to_fire_later",
function (){
alert( "at the time I was defined, 'I_Like_to_Change_Frequently' was " + val)
})
})(I_Like_to_Change_Frequently);
var I_Like_to_Change_Frequently = undefined
答案 1 :(得分:0)
Function.prototype.bind()
:您还可以使用javascript bind()
函数来定义函数的范围。
这样,可以保留创建函数时的变量值。
some_DOM_object.addEventListener( "some_arbitrary_event_to_fire_later", (function I_Need_the_Current_Value(){
alert( "at the time I was defined, 'I_Like_to_Change_Frequently' was " + this.variableAtTheTimeOfCreation)
}).bind({variableAtTheTimeOfCreation: I_Like_to_Change_Frequently}));
在此示例中,我们将函数绑定到范围对象{variableAtTheTimeOfCreation: I_Like_to_Change_Frequently}
。
当处理程序执行时,它的this
将是我们定义并绑定到它的范围对象(创建时)。