wootscootinboogie
wootscootinboogie

Reputation: 8695

Understanding underscore bind

    function checkBalance() {
        return this.balance;
    }

    function Person(name, balance) {
        this.name = name;
        this.balance = balance;
    }


    var me = new Person('tim', 1000);
    _.bind(checkBalance, Person);

    console.log(checkBalance()); //undefined

I know this is a case where checkBalance should be on the Prototype of the Person object, but I'm failing to understand why the bind method isn't working normally here. I've tried both Person and me as the context for _.bind to bind checkBalance, but I keep getting undefined. What's going on here that I'm getting this undefined?

Upvotes: 1

Views: 2376

Answers (1)

Timothy Shields
Timothy Shields

Reputation: 79441

bind(func, obj) returns a new function identical to func except that this inside of the function will refer to obj.

You are binding this in the checkBalance function to the Person function, when it seems like you mean to bind this to me.

Try this:

var f = _.bind(checkBalance, me);
console.log(f()); //1000

Or, reassigning to the same function:

checkBalance = _.bind(checkBalance, me);
console.log(checkBalance()); //1000

Upvotes: 6

Related Questions