4

我正在编写一些 JavaScript 代码。我对这个关键字有点困惑。如何访问dataReceivedHandler函数中的记录器变量?

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

        // more stuff
    }
};
4

3 回答 3

10

您可以在 loadData 函数中执行类似的操作来访问您的对象...

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
    }
};
于 2013-04-05T00:25:14.270 回答
6

假设loadData这样调用:

MyClass.loadData();

然后:

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

    // more stuff
}
于 2013-04-05T00:23:47.080 回答
4

因为dataReceivedHandler是一个匿名函数this,会在全局范围内引用窗口对象。我想了两种方法可以绕过它。

a)在里面创建一个变量loadData来保存它的上下文,然后在里面使用它dataReceivedHandler

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

    // more stuff
}

b) 使用applycall更改匿名函数的上下文。

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
}

由于性能和内存使用优化,我更喜欢选项 B,但两者都可以正常工作。

于 2013-04-05T00:26:54.877 回答