回调函数中的变量作用域
Variable scope in callback function
我的javascript代码遇到了问题。
我有一个类MyClass
,并将函数myFunction
添加到它的原型中。
MyClass.prototype.myFunction = function(file){
if(some condition){
fs.exists("./" + file, function(exists){
if(exists)
console.log(this.someValue);
/* lot of other code */
else
/* do something else */
});
}else{
/* do something */
}
}
我的问题是this.someValue
的范围(例如,我只想打印它)。每当exists
等于true
时,控制台就会记录undefined
,但事实并非如此。如果我要在fs.exists()
之外打印它,那么它有一个值,所以我想这是一个范围问题。
如何访问此示例中的this.someValue
?
提前感谢!
您必须.bind
您的内部函数
MyClass.prototype.myFunction = function(file){
if(some condition){
fs.exists("./" + file, function(exists){
if(exists)
console.log(this.someValue);
/* lot of other code */
else
/* do something else */
}.bind(this));
}else{
/* do something */
}
}
这可以重写为更干净的
MyClass.prototype.myFunction = function myFunction(file){
if(some condition){
fs.exists("./" + file, this.doSomething.bind(this));
}
else{
// do something else
}
}
MyClass.prototype.doSomething = function doSomething(exists) {
if(exists) {
console.log(this.someValue);
// lot of other code
}
else {
// do something else
}
}
我个人喜欢这个解决方案,因为它可以让你保持出色的代码组合,并防止你嵌套function(){ function(){ function(){ ... }}}
。它还可以防止一堆var that = this;
或var self = this;
变量四处浮动,让您怀疑哪个范围是哪个范围。
是的,.bind
速度较慢,但正如minitech所指出的,与文件访问相比,它肯定不会成为您的瓶颈。
MyClass.prototype.myFunction = function(file){
var that = this;
// some lines of code later...
console.log(that.someValue);
}
As this
-是由函数范围定义的关键字,用于响应函数的所有者或调用方。因此,您可以将其指针存储在另一个变量中:
MyClass.prototype.myFunction = function(file) {
if(some condition) {
var self = this; // create variable with pointer to 'this'
fs.exists("./" + file, function(exists) {
if(exists) {
console.log(self.someValue); // we can access it to parent scope variables
/* lot of other code */
} else {
/* do something else */
}
});
} else {
/* do something */
}
}
我们不妨看看这个精彩的话题:;这个";关键词工作?
相关文章:
- 带有KendoUI组件的Javascript变量作用域
- Javascript变量作用域:从回调函数中提取变量
- 使用JavaScript回调函数了解变量作用域和闭包
- jquery.post和变量作用域
- 变量作用域:在函数之间传递的名称
- 在 AJAX 和 Javascript 中使用变量和变量作用域
- 节点.js/express.js中的变量作用域
- jquery ajax 回调变量作用域(为什么有些在作用域中,而另一些则不在作用域中)
- JavaScript 中的变量作用域
- ajax GET 和 POST 中的变量作用域
- Javascript:变量作用域和全局变量的弊端
- Javascript 自执行函数和变量作用域
- 拼接上的Javascript全局变量作用域/覆盖
- 在Node中与jsdom和jquery共享变量作用域
- NodeJS:代码优化和变量作用域
- Javascript数组变量作用域
- AngularJS ng控制器指令不接受javascript中的变量(作用域函数),也不给出任何错误
- 回调函数中的变量作用域呢
- JavaScript/jQuery变量作用域导致错误
- AJAX变量作用域