最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Javascript "this" scope - Stack Overflow

programmeradmin4浏览0评论

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
    }
};

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
    }
};
Share Improve this question asked Apr 5, 2013 at 0:21 bluetechbluetech 1,4603 gold badges15 silver badges22 bronze badges
Add a comment  | 

3 Answers 3

Reset to default 10

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
    }
};

Assuming loadData is called like so:

MyClass.loadData();

then:

loadData: function() {
    var self = this;
    var dataReceivedHandler = function() {
        self.logger ...
    }

    // more stuff
}

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)

  1. 暂无评论