【发布时间】:2015-03-31 19:09:59
【问题描述】:
我目前正在特别学习 JS 和 ES6。我无法理解为什么我的带有类构造函数和箭头函数的代码如果不进行一些更改就无法工作。
这是我开始的地方,一个 ES6 模块导出这个类似通量的调度程序对象。
// 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)
})
}
})
}
}
由于我不知道的原因,这不起作用。
- 第一个
.forEach(...)结果为Uncaught TypeError: Cannot read property 'forEach' of undefined,就好像数组没有定义一样。 -
var args = [].slice.call(arguments)导致 args 是一个零长度数组,而不是实际上,嗯,有参数。
为了使代码正常工作,我将其更改为:
// 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)
})
}
})
}
}
因此,错误已由
修复- 声明一个数组并在上面调用
.forEach,然后 - 使用常规回调函数而不是箭头函数。
请解释为什么带有内联数组的forEach 会失败,以及为什么从箭头函数内部切片参数列表会失败。
另外,额外的问题,为什么'this.stores.foreach'中的this绑定到我的对象实例而不是例如导致函数被调用的事件?
【问题讨论】:
-
如果使用分隔符
;,是否还会出现错误?你好像对它们过敏 -
正确,缺少分号是错误 #1 的原因。我不过敏,但我看过的几个库似乎省略了分隔符。我只需要学习规则并采用约定来使用或不使用它们。不过,使用它们似乎更安全。
标签: javascript arrays class module ecmascript-6