1

So, below is a very barebones example of a case where I'd set that to this so I can use the scope of myObj. How would I integrate Function.prototype.bind, just so I can see how I can use it in the future?

var myObj = {

        specialFunction: function () {

        },

        anotherSpecialFunction(){

        },

        getAsyncData: function (cb) {
            // an operation
            cb();
        },

        render: function () {
            var that = this;
            this.getAsyncData(function () {
                that.specialFunction();
                that.anotherSpecialFunction();
            });
        }
    };

    myObj.render();
5
  • that would give the scope of render function in your case and not of myObj Commented Oct 7, 2013 at 14:50
  • @Vandesh I don't think you're right there... Commented Oct 7, 2013 at 14:51
  • Where is getAsyncData defined? Is it suppose to be myObj.getAsyncData? Commented Oct 7, 2013 at 14:52
  • @Musa Yes, sorry. Type whilst typing up code... Commented Oct 7, 2013 at 14:53
  • @benhowdle89 : correct. My bad! Verified here - jsfiddle.net/FKduF :) Commented Oct 7, 2013 at 14:55

3 Answers 3

2

Just use bind on the method you want and specify the context

render: function () {
    this.getAsyncData(this.specialFunction.bind(this));
}

    render: function () {
        this.getAsyncData(someFunction.bind(this));
        function someFunction() {
            this.specialFunction();
            this.anotherSpecialFunction();
        }
    }
Sign up to request clarification or add additional context in comments.

1 Comment

That's cool. Maybe I made it too contrived. I've edited it to reflect what I'd be more likely to do in a real life use case.
1

How would I integrate Function.prototype.bind

Omit that, use this instead and bind the function to the instance:

…
    render: function () {
        this.getAsyncData(function () {
            this.specialFunction();
            this.anotherSpecialFunction();
        }.bind(this));
    }
…

just so I can see how I can use it in the future?

You can use it right now. Every decent browser supports it, and if you really care about old Internet Explorers and the like you can shim it.

Comments

0

If you wanted this to still refer to myObj inside the callback function passed to getAsyncData you'd want your render function to look like this:

render: function () {
    this.getAsyncData((function () {
        this.specialFunction();
        this.anotherSpecialFunction();
    }).bind(this));
}

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.