[英]ES6 Class Variables Out of Scope?
剛剛切換到運行io.js的ES6。
我正在編寫一些類代碼,但是出現意外錯誤。
'use strict';
var _ = require('lodash');
class Country {
constructor(blocked) {
this.blocked = ['USA'];
}
ok(input) {
console.log('Receiving...',input['country']);
console.log('Blocked:', this.blocked);
if(_.includes('USA', input['country'])) {
return -1;
}
return 0;
}
}
module.exports = Country;
無論出於什么原因, 除了 this.blocked
類變量之外 ,其他所有東西都運行良好。
當我進行控制台日志記錄時,它顯示為Blocked: undefined
。
關於這里發生的事情有什么想法嗎?
加成
我在另一個類中調用該函數,如下所示...
var Country = require('./filters/country.js');
var country = new Country();
class FilterClassifier {
constructor() {
var self = this;
self.filters = [country.ok];
}
userFilter(params) {
var self = this;
var input = {
country : params.country,
};
console.log(self.filters[0](input));
}
}
module.exports = FilterClassifier;
如注釋中所述,調用函數的方式刪除了函數的上下文。
self.filters = [country.ok];
接着
console.log(self.filters[0](input));
意味着this
里面ok
將不country
。 你需要做
self.filters = [country.ok.bind(country)];
要么
self.filters = [() => country.ok()];
我建議你閱讀了this
在JavaScript。 在這種特殊情況下的簡短答案是, this
是根據調用函數的方式定義的。
var a = {};
a.fn = function(){};
var b = {};
b.fn = a.fn;
b.fn();
調用b.fn()
, this
函數內部為b
。 這是因為當使用foo.bar()
形式調用函數時, this
函數內部的對象被定義為調用該函數的對象( foo
)。 就你而言
self.filters[0]();
這意味着, this
里面你ok
功能實際上是self.filters
出於同樣的原因。
如果你有一個具體的this
是重要的,它是你的責任,以確保你繞過一個功能,您將通過設置適當的功能this
。 使用fn.bind(foo)
將返回一個新函數,該函數在調用時使用給定的this
調用fn
。
它看起來像this.blocked
的作用范圍是constructor
函數, this
在ok
沒有被叫標識blocked
。
編輯 :我錯了,謝謝Pointy。 為了幫助那些偶然發現這篇文章的人,我不會刪除我的錯誤答案,而是分享我學到的東西。 大衛,在評論中,您要求找到一種解決方法。 this
可以替換為設變量 ,以避免混淆,或使用this
與bind()
當一個函數被調用。
class Country {
// variable scoped to class with let
// set blocked = value in constructor
// should not need 'this.' nor 'bind()'
let blocked = [];
...
}
“ 確定this
說:”你不得不默認 this
綁定:不確定。 您希望使用隱式綁定,並希望顯式綁定可以與country.ok.bind(country)
。
進一步的閱讀說明了胖箭頭=>
和var self = this;
使this
令人困惑。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.