4

In C++, you have a bind function that allows you to bind parameters to functions. When you call the function, it will be called with those parameters. Similarly, MySQL has an ability to bind parameters to queries where it will substitute question marks with the variable. In Javascript and jQuery, the bind function has a confusingly different meaning. It makes the passed parameter the this variable, which is not at all what I want. Here's an example of what I want to achieve:

    var outerVariable;
    var callbacks = [
        some_object.event,
        some_object.differentEvent.bind(outerVariable)
    ];
    // func() will automatically have outerVariable in scope
    $.map(callbacks, function(func) { func(); });
1
  • outerVariable will be in scope regardless, since it is higher up the scope chain than func Commented Jul 15, 2015 at 17:32

3 Answers 3

2

I don't think there is an easy way to use bind without playing around with this, if you want to bind arguments only you may be better writing a wrapper

function bindArgs(fn) {
    var slice = Array.prototype.slice,
        bound_args = slice.call(arguments, 1);
    return function () {
        var args = slice.call(arguments, 0);
        return fn.apply(this, bound_args.concat(args));
    }
}

Now

function foo(a, b) {
    console.log(this, a, b);
}
var bar = bindArgs(foo, 'bar');
var obj = {baz: bar};
obj.baz('baz'); // logs obj, "bar", "baz"
Sign up to request clarification or add additional context in comments.

Comments

1

Do this instead:

var callbacks = [
    some_object.event,
    some_object.differentEvent.bind(some_object, outerVariable)
];

Comments

1

The only difference between the C++ and JavaScript bind is that the JavaScript bind takes one extra argument: thisArg, which will bind the keyword this for the bound function to whatever you pass in. If you do not want to re-bind the this-argument, then pass null as the first parameter, and the rest should look familiar to the C++ variant you speak of:

function add(a, b) {
    return a + b
}

var three = add(1, 2)
var makeThree = add.bind(null, 1, 2)
three = makeThree()

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.