Associate a function with another function in javascript

I have a function in javascript

function foo(callback) { console.log("Hello"); callback(); } 

and other function

 function bar() { console.log("world"); } 

and I want to make a FooBar function

 FooBar = foo.bind(this, bar); 

This works fine, however, what I'm actually trying to do is create a function queue , and often I will have to bind the function parameter to none before bind the callback, as in the following example

 function foo() { console.log(arguments[0]); var func = arguments[1]; func(); } function bar() { console.log("world"); } foo.bind(this, "hello"); var FooBar = foo.bind(this, bar); FooBar(); 

which produces this error

 [Function: bar] TypeError: undefined is not a function 

How can I bind a function to another function when it is bound to other types of functions?

+6
source share
2 answers

You bind "Hello" to foo , and then bind bar to foo separately - you should not bind bar to the result of the first bind , for example:

 var FooHello = foo.bind(this, "hello"); var FooBar = FooHello.bind(this, bar); 

The spell is here. (which says "Hello", "world").

+5
source

The bind method does not bind functions to each other, the goal is to fix the context of the 'this' keyword and any arguments when calling the function. Then it returns a new function, leaving the original unchanged.

So: foo.bind(this, "hello") does not actually work. Calling bind a second time creates a new function with a fixed argument bar . The reason you get the error message is because if only one argument is passed, arguments[1] is undefined.

You can do as Richie suggests and add an intermediate variable, or just pass both arguments in one bind:

 var FooBar = foo.bind(this, "hello", bar); 

It is probably a good idea to also enable runtime checking so that your function detects when it is dealing with the function. This eliminates the need to disturb the order of arguments.

 if(typeof func === 'function'){ func(); } 
+4
source

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


All Articles