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?
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.
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.
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.
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.
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").
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With