What is the difference between these two javascript functions?

I came across two types of functions while studying javascript, I think. I tried to put them lower, as I understand them.

function example(arg1, arg2) { //code to do stuff here }

and

thing.method(function(arg) {
  //code to do stuff here
});

My thinking is that the first case is the creation of a function called an example that takes two arguments, and so on in braces. I believe that a function can be called and used as long as it is in scope (I think this is the right word?).

In the second, I got confused. My thinking is that we have a thing (array, object, whatever), the method is called on this thing (foreach, map, etc.), after which I get stuck. Is there a function that does not have a name? It takes one argument, and everything happens in braces. Suppose it was an array and we called foreach, then the material inside the functional brackets would happen to each element? Why should I use this and not just create a function like the first one that I could just call?

Why can't I just say:

function example(arg) { //stuff }
thing.method(example(arg));

Perhaps I misunderstood some things. Can anyone cleanse me?

+4
source share
2 answers
thing.method(function(arg) {
  //code to do stuff here
});

It uses the so-called anonymous function . , . thing.method(). thing.method() , :

thing: {
    method: function(callback) {
        //...
        callback();
        //...
    }
};

function example(arg) { /* stuff */ }
thing.method(example(arg));

example(arg) thing.method() . , , :

function example(arg) { /* stuff */ }
thing.method(example);

method() , :

thing: {
    method: function(callback) {
        var foo = "bar";
        //...
        callback(foo);
        //...
    }
};
+2

example - , JS. . , , :

example(value1, value2);

value1 value2 , , , . .

AND . , , . (, click, hover ..).

, click thing . thing, . , click.

// jQuery callback on a click event
$("#button-in-your-program").click(function() {
  console.log("Your callback function worked");
});

, , . - , . . , . , , .

+1

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


All Articles