2016-11-15 1 views
0

isDataMatchingnamespaceを呼び出す際に、無効な使用方法があるthisとなり、どのようにしてisDataMatchingnamespaceを適切な方法で呼び出すことができますか? thisthis以降の無効な使用である「これの潜在的に無効な使用法」を克服するにはどうすればよいですか?

function Client() { 

    var namespace = "default"; 

    this.addnamespaceTodata = function(data) { 
     data.namespace = namespace; 
     return data; 
    }; 

    this.isdataMatchingnamespace = function(data) { 
     return data.namespace === namespace; 
    }; 

    this.filterdatasBynamespace = function(datas) { 
     var result = []; 
     _.forEach(datas, function(data) { 
      if (this.isdataMatchingnamespace(data)) { // I get potentially invalid usage of this so how to overcome and how to call isDataMatchingnamespace in a proper way? 
       result.push(data); 
      } 
     }); 
    } 
} 

module.exports = Client; 
+0

「このキーワードはどのように機能しますか?」(http://stackoverflow.com/questions/3127429/how-does-the-this-keyword-work) – Andreas

答えて

4

は、その関数内undefinedあります。

underscore.jsには、オプションの追加引数をforEachに渡して、関数内に含める対象を指定することができます(this)。あなたはそれが機能外部からthisと同じになるようにしたい場合は、_.forEachへの3番目の引数としてthisを渡す:

_.forEach(datas, function(data) { 
     if (this.isdataMatchingnamespace(data)) { 
      result.push(data); 
     } 
    }, this); // Added ", this" 
1

他の方法は、変数にこの値を格納することでもあります。

のはvar _thisRef = this;var namespace = "default";の下にこれを定義し、次のようにあなたのコード

あなたの更新されたコードを変更せずに_thisRef.isdataMatchingnamespace(data)を使用しましょう:

function Client() { 

var namespace = "default"; 
var _thisRef = this; 

this.addnamespaceTodata = function(data) { 
    data.namespace = namespace; 
    return data; 
}; 

this.isdataMatchingnamespace = function(data) { 
    return data.namespace === namespace; 
}; 

this.filterdatasBynamespace = function(datas) { 
    var result = []; 
    _.forEach(datas, function(data) { 
     if (_thisRef.isdataMatchingnamespace(data)) { // I get potentially invalid usage of this so how to overcome and how to call isDataMatchingnamespace in a proper way? 
      result.push(data); 
     } 
    }); 
} 
} 

module.exportsは=クライアント。

関連する問題