1

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?

1
  • bind doesn't do what you think it does! Commented Oct 12, 2015 at 22:22

3 Answers 3

5

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);
Sign up to request clarification or add additional context in comments.

Comments

2

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 :)

Comments

2

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); };

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.