2

我有一个简单的例子:

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() ...

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

4

3 回答 3

5
  • 创建局部变量并存储在那里'this'

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

  • 将“this”绑定到内部函数:读取:function() {

     fs.readFile(this.name, function (err, data) {
         ...
         this.text = data;
         ...
     }.bind(this)
    

    },

Note: It's insufficiently to store data to this.text: if you read something asynchronously in yur class, you need to provide callbacks to let other objects know that you got some data in yourFile.text

于 2012-06-11T22:12:23.270 回答
4

您可以保存this对闭包外部的引用并从内部引用它:

File.prototype = {
    read: function() {
        var self = this;
        fs.readFile(this.name, function (err, data) {
            self.text = data;
        });
    },
    getContent: function() {
        return this.text
    }
}
于 2012-06-11T22:03:42.520 回答
0

你可以做几件事:

  1. 创建一个作用域版本this

    File.prototype = {
      read: function() {
        var self = this;
        fs.readFile(this.name, function (err, data) {
          self.text += data;
        });
      }
    };
    
  2. 将函数绑定到 的当前值this

    File.prototype = {
      read: function() {
        fs.readFile(this.name, function (err, data) {
          this.text += data;
        }.bind(this));
      }
    };
    
于 2012-06-11T22:04:25.153 回答