theJava
theJava

Reputation: 15044

Javascript variable name as function

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

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

Upvotes: 2

Views: 2852

Answers (3)

kemiller2002
kemiller2002

Reputation: 115538

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

Upvotes: 3

Jakub Hampl
Jakub Hampl

Reputation: 40573

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

Upvotes: 2

Jacob Mattison
Jacob Mattison

Reputation: 51072

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();

Upvotes: 3

Related Questions