如何在异步函数中使用"this"?

Bdf*_*dfy 2 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
     }
}

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() ...
Run Code Online (Sandbox Code Playgroud)

我想在this.text变量中添加文件内容.怎么做 ?

Nay*_*est 5

  • 创建局部变量并存储'this'

    读:function(){var _file = this; fs.readFile(this.name,function(err,data){... _ file.text = data; ...}); },

  • 将'this'绑定到内部函数:read:function(){

     fs.readFile(this.name, function (err, data) {
         ...
         this.text = data;
         ...
     }.bind(this)
    
    Run Code Online (Sandbox Code Playgroud)

    },

注意:将数据存储到this.text是不够的:如果您在yur类中异步读取某些内容,则需要提供回调以让其他对象知道您在yourFile.text中获得了一些数据