开发者

Javascript variable name as function

var johnson = button.addEventListener('click', function() {
}); 

In what ways 开发者_如何学Ci can use this variable name. can i call the johnson as a function somewhere?


No, because you aren't assigning addEventListener function to the variable, you are assigning the returned value from executing the function (which in this case is actually nothing look here for an example of the return value: http://jsfiddle.net/DKyhW/2/ ).

To assign the function you either need to do:

var johnson = button.addEventListener; 
//this assigns the eventlistener function to the variable.
johnson('click', function () {});

or

var johnson = function () {} //assigns function to variable.

button.addEventListener('click', johnson);


johnson will contain the return value of addEventListener, but addEventListener doesn't return anything. johnson will be null.

You can certainly used a named function or a variable that points to a function as an event listener, though:

    var johnson = function() {
      //do stuff
    }

button.addEventListener('click', johnson);

Now you can call that listener function by clicking the button, or by calling

johnson();


Since addEventListener does not have a return value, your variable will be bound to undefined being virtually useless.

Maybe you wanted to something like this:

var johnson = function() { ... }

button.addEventListener('click', johnson);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜