【问题标题】:How to reference object data structure in nested method definition?如何在嵌套方法定义中引用对象数据结构?
【发布时间】:2016-04-10 21:36:45
【问题描述】:

function FormHistory()
{
  this.list = [];
  this.restoreFromFile = function()
  {
    console.log('Restoring History From File');
    fs.readFile('FormHistory.txt', function(err, data) {
      if(err) throw error;
      this.list = data.toString().split("\n");
    });
  }
}

我可以确认数据包含来自文本文件的正确信息,并且拆分正确地标记了文件。但是,由于尝试在 readFile() 的回调中引用 this.list,我似乎遇到了问题。

如何引用该列表?我必须将它传递给回调吗?

【问题讨论】:

  • var self = this 放在外部函数中,并在回调中引用self 而不是this

标签: javascript scope callback


【解决方案1】:

您遇到了问题,因为您的回调函数创建了一个新范围,因此您的回调函数中的 this 不包含对 this.list 的引用。

第一种方法

您可以将上下文保存在一个变量中,然后将该变量用于您的回调函数。

function FormHistory()
{      
//Save the parent context
      var self = this;
      this.list = [];
      this.restoreFromFile = function()
      {
        console.log('Restoring History From File');
        fs.readFile('FormHistory.txt', function(err, data) {
          if(err) throw error;
          //use the parent context in the callback function
          self.list = data.toString().split("\n");
        });
      }
}

第二种方法:ES6 的救援

ES6 的一个新特性是箭头。 与函数不同,箭头与周围的代码共享相同

所以,你的代码变成了:

function FormHistory()
{
  this.list = [];
  this.restoreFromFile = function()
  {
    console.log('Restoring History From File');
    fs.readFile('FormHistory.txt', (err, data) => {
      if(err) throw error;
      //The "this" refers to the parent context, there is no new context
      this.list = data.toString().split("\n");
    });
  }
}

【讨论】:

    【解决方案2】:
    this.list = data.toString().split("\n");
    

    上一行中的“this”引用了 readFile 回调上下文,而不是 FormHistory() 上下文。您必须在某处有引用或绑定回调。

    function FormHistory()
    {
      var self = this;
      this.list = [];
      this.restoreFromFile = function()
      {
        console.log('Restoring History From File');
        fs.readFile('FormHistory.txt', function(err, data) {
          if(err) throw error;
          self.list = data.toString().split("\n");
        });
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-10-16
      • 1970-01-01
      • 2023-03-17
      • 2021-05-31
      • 2021-05-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多