2016-04-10 18 views
0

ネストされたメソッド定義でオブジェクトデータ構造を参照する方法は?

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"); 
 
    }); 
 
    } 
 
}

私は、データをテキストファイルから正しい情報を保持し、分割が正しくファイルをトークン化していることをことを確認することができます。しかし、私はthis.listをreadFile()からのコールバックの中で参照しようとしているために問題に遭遇しているようです。

リストの参照方法を教えてください。コールバックに渡す必要がありますか?

+0

は、外側の関数で 'VARの自己= this'を入れて、代わりにコールバックの内側' this'のself' 'を参照してください。 – Alnitak

答えて

1

コールバック関数は、新しいスコープを作成するので、あなたが問題を持っているので、あなたのコールバック関数内thisthis.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"); 
    }); 
    } 
} 
1
this.list = data.toString().split("\n"); 

上記の 'this'は、FormHistory()コンテキストではなく、readFileコールバックコンテキストを参照します。あなたは参照をどこかに置くか、コールバックをバインドする必要があります。

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"); 
    }); 
    } 
} 
関連する問題