Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bind a function to another function in javascript

I have a function in javascript

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

and another function

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

and I want to make a function FooBar

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 a none function parameter before binding a 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 a I bind a function to another function once it has been bound to other none function types?

like image 658
Loourr Avatar asked Jun 16 '13 20:06

Loourr


People also ask

What does bind () do in JavaScript?

bind is a method on the prototype of all functions in JavaScript. It allows you to create a new function from an existing function, change the new function's this context, and provide any arguments you want the new function to be called with.

What is use of call () apply () bind () methods?

In JavaScript, you can use call() , apply() , and bind() methods to couple a function with an object. This way you can call the function on the object as if it belonged to it. The call() and apply() are very similar methods. They both execute the bound function on the object immediately.

How do you bind variables in JavaScript?

We use the Bind() method to call a function with the this value, this keyword refers to the same object which is currently selected . In other words, bind() method allows us to easily set which object will be bound by the this keyword when a function or method is invoked.

Does bind call function?

The call, bind and apply methods can be used to set the this keyword independent of how a function is called. The bind method creates a copy of the function and sets the this keyword, while the call and apply methods sets the this keyword and calls the function immediately.


1 Answers

You're binding "Hello" to foo, and then separately binding bar to foo as well - shouldn't you bind bar to the result of the first bind, like this:

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

Fiddle here. (which logs "Hello", "world").

like image 57
RichieHindle Avatar answered Nov 15 '22 17:11

RichieHindle