Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript "this" scope

Tags:

javascript

I am writing some JavaScript code. I am a little confused about this keyword. How do I access logger variable in the dataReceivedHandler function?

MyClass: {
    logger: null,
    init: function() {
        logger = LogFactory.getLogger();
    },
    loadData: function() {
        var dataReceivedHandler = function() {
            // how to access the logger variable here? 
        }

        // more stuff
    }
};
like image 879
bluetech Avatar asked Nov 30 '22 04:11

bluetech


1 Answers

You can do something like this inside the loadData function to access your object...

MyClass: {
    logger: null,
    init: function() {
        this.logger = LogFactory.getLogger();
    },
    loadData: function() {
        var self = this;
        var dataReceivedHandler = function() {
            // how to access the logger variable here? 
            self.logger.log('something');
        }

        // more stuff
    }
};
like image 91
doowb Avatar answered Dec 04 '22 11:12

doowb