user1413969
user1413969

Reputation: 1291

Binding a value to a function in javascript

Lets say I have this function:

function toy(input) {
    return input + 1;
}

I want to essentially generate a function that will print 4 by binding 3 to input. So that I could call something like fn() and it will print 4.

So I tried doing:

var fn = toy.bind(3);

Then when I executed fn(), I'm not getting 4.

Do I need to use 'this' in order to make this work/Is there a way to do this without bind?

Upvotes: 1

Views: 64

Answers (3)

Felix Kling
Felix Kling

Reputation: 816404

Is there a way to do this without bind?

Yes:

var fn = function() { return toy(3); };

Or if you want to pass fn's this along:

var fn = function() { return toy.call(this, 3); };

Upvotes: 2

Amit
Amit

Reputation: 46323

The first argument passed to .bind() is used as the this in the called function. The first argument to be pass to the called function is the second parameter passed to .bind(). You can use a meaningful this binding if there is one, or just use null if the function ignores this:

var fn = toy.bind(null, 3);

Upvotes: 5

Tiago Romero Garcia
Tiago Romero Garcia

Reputation: 1078

The first argument of bind is the context of this so you need to pass 3 as the 2nd argument:

var fn = toy.bind(this, 3);

Then it will work :)

Upvotes: 2

Related Questions