Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript - scope is lost in callback

Tags:

javascript

I have the following code:

var myPage = {};
myPage.component = function(callback){

    var somethingHappened = true;

    if (somethingHappened){
        callback();
    }
};

myPage.main = function(){

    // Initialise.
    this.init = function(){

        // make an instance of my component
        this.component = new myPage.component( this.callback );

        // need my utility function here
        this.doSomethingUseful();
    };

    // Callback to be executed when something happs in the component.
    this.callback = function(){
        this.doSomethingUseful(); // doesn't work
    };

    // A useful utility that needs to be accessible from both the 
    // init() and callback() functions
    this.doSomethingUseful = function(){
        // some utility stuff
    };
};
new myPage.main().init();

What's the best way for me to ensure that the myPage.main scope is available when the callback function is executed from the component?

like image 822
Xoundboy Avatar asked Jan 15 '23 04:01

Xoundboy


2 Answers

use bind:

this.callback = function(){
    this.doSomethingUseful(); // doesn't work
}.bind(this);
like image 105
Matt Whipple Avatar answered Jan 18 '23 23:01

Matt Whipple


If you want to supply scope, you can use Function.prototype.call.

var foo = 'bar';
function(){
  // this = 'bar';
}.call(foo);
like image 21
Brad Christie Avatar answered Jan 19 '23 00:01

Brad Christie