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”绑定到内部函数: 读:函数(){

      },

    注: 将数据存储到此文件中是不够的。text:如果您在yur类中异步读取某些内容,则需要提供回调以让其他对象知道您的file.text中有一些数据