我的 javascript 代码遇到了问题。
我有一个类 MyClass
并在其原型(prototype)中添加了函数 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 指出的那样,与文件访问相比,它肯定不会成为您的瓶颈。
关于javascript - 回调函数中的变量范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17529563/