2015-03-31 80 views
2

我目前特別學習JS和ES6。我無法理解爲什麼我的代碼具有類構造函數和箭頭函數,沒有一些更改就無法正常工作。ES6類構造函數和箭頭函數的解釋效果

這裏是我開始的地方,一個ES6模塊導出這個類似flux的調度器對象。

// RiotControl dispatcher formatted as ES6 module. 
// https://github.com/jimsparkman/RiotControl 

var dispatcher = { 
    stores: [], 
    addStore: function(store) { 
    this.stores.push(store); 
    } 
}; 

['on','one','off','trigger'].forEach(function(api){ 
    dispatcher[api] = function() { 
    var args = [].slice.call(arguments); 
    this.stores.forEach(function(el){ 
     el[api].apply(null, args); 
    }); 
    }; 
}); 

export default dispatcher 

我想作一類出這個代碼,並最初以結束:

// RiotControl dispatcher formatted as ES6 class module. 
// https://github.com/jimsparkman/RiotControl 

export default class { 
    constructor() {   
    this.stores = []  
    this.addStore = store => { 
     this.stores.push(store); 
    } 

    ['on','one','off','trigger'].forEach(fn => { 
     this[fn] =() => { 
     var args = [].slice.call(arguments) 
     this.stores.forEach(function(el){ 
      el[fn].apply(null, args) 
     }) 
     } 
    }) 
    } 
} 

不知什麼原因對我來說,這是行不通的。

  1. 第一個.forEach(...)結果爲Uncaught TypeError: Cannot read property 'forEach' of undefined,就好像該數組沒有定義一樣。
  2. var args = [].slice.call(arguments)結果args是一個零長度數組,而不是實際上,umm,有參數。

要獲取該代碼的工作,我把它改成這樣:

// RiotControl dispatcher formatted as ES6 class module. 
// https://github.com/jimsparkman/RiotControl 

export default class { 
    constructor() {   
    this.stores = []  
    this.addStore = store => { 
     this.stores.push(store); 
    } 

    var api = ['on','one','off','trigger'] 
    api.forEach(fn => { 
     this[fn] = function() { 
     var args = [].slice.call(arguments) 
     this.stores.forEach(function(el){ 
      el[fn].apply(null, args) 
     }) 
     } 
    }) 
    } 
} 

因此,錯誤是由

  1. 固定聲明數組,並呼籲.forEach上和
  2. 使用常規回調函數而不是箭頭函數。

請解釋爲什麼帶內聯數組的forEach失敗,以及爲什麼從箭頭函數內部切割參數列表失敗。

此外,獎金問題,爲什麼在'this.stores.foreach`綁定到我的對象實例,而不是例如。導致函數被調用的事件?

+0

如果你使用分隔符'';你還會得到錯誤嗎?你似乎對它們過敏 – 2015-03-31 19:13:41

+0

正確,錯誤的分號是錯誤#1的原因。我沒有過敏,但我看過的幾個圖書館似乎忽略了分隔符。我只需要學習規則並採用慣例來使用或不使用它們。不過,使用它們似乎更安全。 – 2015-03-31 20:15:57

回答

1

請解釋爲什麼帶內聯數組的forEach失敗,爲什麼從箭頭函數內部切割參數列表失敗。

的代碼被解釋如下:

this.addStore = store => { ... }['on','one','off','trigger'].forEach(...) 
// which becomes 
this.addStore = store => { ... }['trigger'].forEach(...) 

即您正嘗試訪問函數的trigger屬性,該屬性當然不存在。使用分號函數定義之後明確終止賦值表達式:

this.addStore = store => { 
    this.stores.push(store); 
}; 
['on','one','off','trigger'].forEach(...); 

而且,獎金問題,這是爲什麼在this.stores.foreach綁定到我的對象實例,而不是如導致函數被調用的事件?

this這裏沒有綁定。 this引用的內容取決於函數的調用方式,您不應該顯示該函數。


var args = [].slice.call(arguments)結果在args是一個零長度的數組代替實際上,UMM,具有的參數。

在箭頭函數中,thisarguments都在詞彙範圍內。即箭頭功能沒有自己的arguments對象。

+0

謝謝,優秀的答案!現在你已經解釋了它的完美意義。 – 2015-03-31 20:17:43

+0

如果可以的話,請在你的回答中編輯這個錯字:這個指的是什麼,取決於函數的調用方式,你不應該顯示。 – 2015-04-08 06:19:53