Last Updated: February 25, 2016
·
674
· kfwerf

Never lose scope again by binding

I hate losing scope in Javascript, however i like that it is quite flexible to what this should be in any situation. There are a few ways to achieve no issues with scope when moving into inner functions.

** Vanilla JS **

var myFoo = function() {
    var parent = this, myBar;

    myBar = function() {
        console.debug( 'parent is', parent, 'i am', this );
    }

    myBar()
}

or

var myFoo = function() {
    var myBar;

    myBar = (function() {
        console.debug( 'i am', this );
    }).bind(this);

    myBar()
}

** Coffeescript **

myFoo = ->
    myBar = ( ->
        console.debug 'i am ', @
    ).bind @

    myBar()

or

myFoo = ->
    myBar =>
        console.debug 'i am', @

    myBar()

I really like the bind solution as it is a way to set binding to the scope and it allows for interesting scenarios, where you can dynamically alter the binding on an anonymous function.

However bind is slower than lexical scope, so i feel that even though i prefer .bind(this) over self = this it will remain the best practice.

Hope this is helpful, i really like the .bind(this) to use over self = this. It saves a lot of issues and keeps my code clear

2 Responses
Add your response

For better cross browser support (bind does not work in all browsers) you can use apply or call, which both have the added advantage of combining the contextual bind with the actual function execution, so instead of .bind(this); myBar() you can just do .apply(this).

over 1 year ago ·

Thanks for the comment, but if .apply and .call immediately invoke the function, don't they? For instance say im doing something like

myFoo.success myBar.apply(@) then it will execute before its called via success cause it calls it immediately where .bind then has the benefit of wrapping the this in there and not actually executing it. I have a lot of times that im using some plugin or framework where i do not actually control the function execution, else i prefer .apply if i can help it.

over 1 year ago ·