最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Javascript variable name as function - Stack Overflow

programmeradmin1浏览0评论
var johnson = button.addEventListener('click', function() {
}); 

In what ways i can use this variable name. can i call the johnson as a function somewhere?

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

In what ways i can use this variable name. can i call the johnson as a function somewhere?

Share Improve this question asked Apr 19, 2011 at 13:20 theJavatheJava 15k48 gold badges134 silver badges174 bronze badges 1
  • Missing 3rd argument for addEventListener – user422039 Commented Apr 19, 2011 at 13:46
Add a ment  | 

3 Answers 3

Reset to default 3

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/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)

  1. 暂无评论