我目前正在学习 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
在“this.stores.foreach”中绑定(bind)到我的对象实例而不是例如导致函数被调用的事件?
最佳答案
Please explain why the
forEach
with an inline array fails and why slicing the arguments list fails from inside the arrow function.
代码解读如下:
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(...);
Also, bonus question, why is this in
this.stores.foreach
bound to my object instance and not e.g. the event that causes the function to be called?
this
没有绑定(bind)在这里。 this
指的是什么取决于函数的调用方式,您不应该显示它。
var args = [].slice.call(arguments)
results in args being a zero length array instead of actually, umm, having the arguments.
在箭头函数中,this
和arguments
都是词法范围的。 IE。箭头函数没有自己的 arguments
对象。
关于javascript - 解释ES6类构造函数和箭头函数的作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29376558/