benhowdle89
benhowdle89

Reputation: 37494

Unexpected token "." when using .bind() in JavaScript

Was just trying out a proof of concept with .bind() and noticed that if I try to use .bind() in this code, I get an unexpected token ".":

var myObj = {
    foo: function(){
        function bar(){
            console.log(this);
        }.bind(this); // errors
        bar();
    }
}

myObj.foo();

However, if I do this:

var myObj = {
    foo: function(){
        var bar = function(){
            console.log(this);
        }.bind(this);
        bar();
    }
}

myObj.foo();

It's fine. No errors. Can someone explain this behaviour please? I'm guessing it's to do with when the function is parsed, but if someone has a more in-depth explanation, that'd be great!

Upvotes: 4

Views: 1315

Answers (1)

kamituel
kamituel

Reputation: 35960

bind() is a method on Function.prototype. Thus it's supposed to be called on the function object and will return a new function with the same body but different value bound to this.

When using function declaration (your first scenario), you'll not getting a function object in return (your first scenario), thus error. There is nothing to call bind() on.

Second one works, because your assigning a function to the variable, so you get a function object.

Consider:

function a() {
   return this.variable;
}

a(); // === undefined, because "this" is bound to the global object, 
     // and global object does not have "variable" defined.
     // When not in strict mode, global object === window (in browser env).

var b = window.a.bind({variable: 'value'});
    // Since a() was declared, it is a property of the global object (window).
    // Lets get it and bind to some object.

b(); // === 'value' - because 'b' is essentialy 'a' bound to {variable: 'value'}.

window.variable = 'other value';  // assign variable to global object
a(); // === 'other value'
b(); // === 'value' - it is not bound to global object, so no change here.

So in your example you could do:

var myObj = {
    foo: function(){
        function bar(){
            console.log('this', this);
        }

        var bar2 = bar.bind(this);
        bar2();

        // Or:
        // bar.bind(this)();
    }
}

Upvotes: 4

Related Questions