Javascript “this” scope

后端 未结 3 1412
耶瑟儿~
耶瑟儿~ 2020-12-11 08:23

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



        
相关标签:
3条回答
  • 2020-12-11 08:55

    Because dataReceivedHandler is an anonymous function this will refer to the window object on the global scope. I think of two way you can bypass that.

    a) Create a variable inside loadData to hold it's context then use it inside dataReceivedHandler as such:

    loadData: function() {
        var self = this;
        var dataReceivedHandler = function() {
            console.log(self.logger);
        }
    
        // more stuff
    }
    

    b) Change the context of your anonymous function using apply or call.

    loadData: function() {
        var dataReceivedHandler = function() {
            console.log(this.logger);
        }
        // more stuff
        dataReceivedHandler.call(this); // by passing this as the first argument we make sure the context of the excuted function is our current scope's this
    }
    

    I prefer option B due to performance and memory usage optimizations, but both would work just fine.

    0 讨论(0)
  • 2020-12-11 09:00

    Assuming loadData is called like so:

    MyClass.loadData();
    

    then:

    loadData: function() {
        var self = this;
        var dataReceivedHandler = function() {
            self.logger ...
        }
    
        // more stuff
    }
    
    0 讨论(0)
  • 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
        }
    };
    
    0 讨论(0)
提交回复
热议问题