Node.js 如何使用;这";在异步函数中?
我举一个简单的例子:Node.js 如何使用;这";在异步函数中?,node.js,Node.js,我举一个简单的例子: function File(name) { this.name = name this.text = null } File.prototype = { read: function() { fs.readFile(this.name, function (err, data) { } }, getContent: function() { return this.text } }
function File(name) {
this.name = name
this.text = null
}
File.prototype = {
read: function() {
fs.readFile(this.name, function (err, data) {
}
},
getContent: function() {
return this.text
}
}
var myfile = new File('my_file')
watch.createMonitor('my_file_dir', function (monitor) {
monitor.files['my_file']
monitor.on("change", function (f, stat) {
myfile.read()
}
})
main program....:
myfile.getContent() ...
我想在这个.text变量中添加文件内容。如何操作?您可以在闭包外部保存对该的引用,并从内部引用它:
File.prototype = {
read: function() {
var self = this;
fs.readFile(this.name, function (err, data) {
self.text = data;
});
},
getContent: function() {
return this.text
}
}
你可以做几件事:
File.prototype = {
read: function() {
var self = this;
fs.readFile(this.name, function (err, data) {
self.text += data;
});
}
};
File.prototype = {
read: function() {
fs.readFile(this.name, function (err, data) {
this.text += data;
}.bind(this));
}
};
File.prototype = {
read: function() {
var self = this;
fs.readFile(this.name, function (err, data) {
self.text += data;
});
}
};
File.prototype = {
read: function() {
fs.readFile(this.name, function (err, data) {
this.text += data;
}.bind(this));
}
};
- 创建局部变量并将其存储在“this” 读:函数(){ var _file=this; fs.readFile(this.name,函数(err,data){ ... _file.text=数据; ... }); },
- 将“this”绑定到内部函数: 读:函数(){ },