How to pass arguments to addEventListener listener function?

前端 未结 30 2273
谎友^
谎友^ 2020-11-21 23:56

The situation is somewhat like-

var someVar = some_other_function();
someObj.addEventListener(\"click\", function(){
    some_function(someVar);
}, false);
<         


        
30条回答
  •  孤独总比滥情好
    2020-11-22 00:55

    Function.prototype.bind() is the way to bind a target function to a particular scope and optionally define the this object within the target function.

    someObj.addEventListener("click", some_function.bind(this), false);
    

    Or to capture some of the lexical scope, for example in a loop:

    someObj.addEventListener("click", some_function.bind(this, arg1, arg2), false);
    

    Finally, if the this parameter is not needed within the target function:

    someObj.addEventListener("click", some_function.bind(null, arg1, arg2), false);
    

提交回复
热议问题