Javascript“这个”范围
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15823948/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript "this" scope
提问by bluetech
I am writing some JavaScript code. I am a little confused about this keyword. How do I access logger variable in the dataReceivedHandler
function?
我正在编写一些 JavaScript 代码。我对这个关键字有点困惑。如何访问dataReceivedHandler
函数中的记录器变量?
MyClass: {
logger: null,
init: function() {
logger = LogFactory.getLogger();
},
loadData: function() {
var dataReceivedHandler = function() {
// how to access the logger variable here?
}
// more stuff
}
};
回答by doowb
You can do something like this inside the loadData function to access your object...
你可以在 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
}
};
回答by Matt Ball
Assuming loadData
is called like so:
假设loadData
是这样调用的:
MyClass.loadData();
then:
然后:
loadData: function() {
var self = this;
var dataReceivedHandler = function() {
self.logger ...
}
// more stuff
}
回答by iMoses
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.
因为dataReceivedHandler
匿名函数this
会在全局范围内引用 window 对象。我想到了两种方法可以绕过它。
a) Create a variable inside loadData
to hold it's context then use it inside dataReceivedHandler
as such:
a) 在里面创建一个变量loadData
来保存它的上下文,然后在里面使用它dataReceivedHandler
:
loadData: function() {
var self = this;
var dataReceivedHandler = function() {
console.log(self.logger);
}
// more stuff
}
b) Change the context of your anonymous function using applyor 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.
由于性能和内存使用优化,我更喜欢选项 B,但两者都可以正常工作。