Difference between two jquery links

function runSomething () {
  // some stuff happens
}

$(selector).bind('event', runSomething());

$(selector).bind('event', runSomething);

What is the difference between these two versions of binding?

Here is an example: http://jsbin.com/icajo/edit

Can someone explain why it works the way it does.

I'm trying to get some buttons to trigger a function in an event, what should I do?

+3
source share
5 answers

In javascript, passing a set of parameters to a function, calls the function, it is calculated on the return value of the function.

var test = function() { return 1; } // Creates a new function that returns 1
alert(test.toString()); // => "function () { return 1; }"
alert(test().toString()); // => "1"

Even alertby itself is just a variable that points to a function.

alert(alert); // => "function alert() { [native code] }"

, , runSomething(), , bind(). alert() , undefined bind()

, runSomething, bind(). Bind , .

, , , (, ) ...

var counter = 0;
function GenerateNext() {
   counter++;
   return new Function("alert(" + counter + ")");
}

a = GenerateNext();
b = GenerateNext();
b() // will alert 2
a() // will alert 1

$(selector).bind('event', GenerateNext());    // alert 3
$(selector).bind('event', a);   // alert 1
$(selector).bind('event', b);   // alert 2

, ; .

0

runSomething(), - .


@JSNewbie, , .

function runSomething () {
    return 3;
}

var a1 = runSomething();
var a2 = runSomething;
alert(a1);
alert(a2);
+5

runSomething , , , , , runSomething , .

runSomething , .

0

$(selector).bind('event', 'runSomething()'); ( 'runSomething()') runSomething(), .

$(selector).bind('event', runSomething); runSomething() , , , , currentTarget ( ) (mousemove X, Y ).

, , , .

function runSomething(event){
   console.log(event); // this would show the event object if the second code is used.
}
0

In javascript functions are treated as variables. Adding "()" will call the function and pass the result to the function (which may be "undefined" if the function returns nothing). The second method is the correct way to use the bind method, since it provides a function handle to call when the event fires.

0
source

Source: https://habr.com/ru/post/1752106/


All Articles