exebook
exebook

Reputation: 33900

Mastering Javascript Function.bind()

function def() {
    console.log(this.x)
}

var f = def.bind({ x:777 })
f() // prints 777

The bind creates a function f which is identical to def, except that within f, this is set to { x:777 }.

Is it possible to access the object f was bound to outside of f? E.g., console.log(f.this.x) (but that doesn't work). Or is it impossible for code that comes after to see what object f was bound to?

Upvotes: 3

Views: 4661

Answers (2)

Tim Goodman
Tim Goodman

Reputation: 23976

I found some useful information on bind here: http://dmitrysoshnikov.com/notes/note-1-ecmascript-bound-functions/

bind as specified in ECMAScript 5 produces a sort of lightweight function (which differs in some ways from usual functions, as described in the link above. Basically it provides a wrapper for calling the target function, and maintains internal properties which include the target function, the bound this, and the bound arguments. As these are internal properties, they aren't accessible in the way the OP is asking about (you can't take an arbitrary bound function f and do something like f.getBoundThis()).

It's worth noting that bind is not unique in capturing some state. Closures also capture state. However, bind (as specified in ECMAScript 5) is not a closure, because closures capture variables whereas bind captures values.

Here's an example:

(function () {
    var x = 2;

    function thisSquared() { return this * this; }
    f = thisSquared.bind(x);

    g = function() { return x * x; } // g is a closure

    console.log(f()); // Squares the captured value (2), prints 4
    console.log(g()); // Squares x, prints 4

    x = 3;
})();

console.log(f()); // Squares the captured value (still 2), prints 4
console.log(g()); // Squares x, prints 9

Some previous implementations of bind (written in JavaScript before ECMAScript 5) didn't have this distinction from closures.

Upvotes: 8

Rob M.
Rob M.

Reputation: 36511

No, you cannot access it because the object is only bound temporarily to the function for the lifetime of the call, it does not change the functions prototype.

Upvotes: 0

Related Questions