8

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?

2 Answers 2

7

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").

Sign up to request clarification or add additional context in comments.

1 Comment

For a less convoluted example see jsfiddle.net/XM4kQ/8. and read up on bind here developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… as the example this fiddle links to makes it look like you are actually binding bar to a bind of foo...
4

The bind method doesn't bind functions to one another, it's purpose is to fix the context of the 'this' keyword and any arguments when the function is called. It then returns a new function, leaving the original unchanged.

So: foo.bind(this, "hello")actually has no effect. Calling bind the second time creates a new function with a fixed argument of bar. The reason you get an error is because with only one argument passed, arguments[1] is undefined.

You could do as Richie suggests and add an intermediate variable, or just pass both arguments in a single bind:

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

It is probably a good idea to also include run time checking so your function can detect when it is dealing with a function. This will save you having to worry about argument order.

if(typeof func === 'function'){
  func();
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.