//绑定元素
Img.prototype._bind = function() {
console.log('classfied',this.classified)
console.log('all',this.all)
console.log('this.figures',this.figures)
methods.$('.__Img__classify' , this.wrap).addEventListener('click',(e) =>{
if(e.target.nodeName !== 'LI') return;
console.log("Img.prototype._bind -> target", e.target)
const type = e.target.innerText
const els = this._getImgsByType(type)
let prevImgs = this.figures.map(figure =>methods.$('img',figure).src) //找出当前每个fugure中包含的图片的src
console.log("Img.prototype._bind -> prevImgs", prevImgs)
let nextImgs = els.map(figure => methods.$('img',figure).src)
const diffArr = this._diff(prevImgs,nextImgs)
console.log('diffArr',diffArr)
})
}
这是老师教的ES6切换图片中绑定元素的实现方法,我不太理解的是第七行那个(e),现在是我自己改好的,也有相同的效果
老师原本的是这样的
//绑定元素
Img.prototype._bind = function() {
console.log('classfied',this.classified)
console.log('all',this.all)
console.log('this.figures',this.figures)
methods.$('.__Img__classify' , this.wrap).addEventListener('click',({target}) =>{
if(target.nodeName !== 'LI') return;
console.log("Img.prototype._bind -> target", target)
const type = target.innerText
const els = this._getImgsByType(type)
let prevImgs = this.figures.map(figure =>methods.$('img',figure).src) //找出当前每个fugure中包含的图片的src
console.log("Img.prototype._bind -> prevImgs", prevImgs)
let nextImgs = els.map(figure => methods.$('img',figure).src)
const diffArr = this._diff(prevImgs,nextImgs)
console.log('diffArr',diffArr)
})
}
那里面的{target}是因为解构赋值才默认是e.target吗,箭头函数这样写解购赋值一定默认最初的参数是e吗,什么时候解构赋值用[]什么时候用{}啊,求教,有点晕
e是lambda表达式(箭头函数)的参数,这是一个回调函数,按了按钮以后,会自动传进来。
因为是参数,写e或者abc,eee都是可以的(只要参数和里面的使用一致)
好比
function isOdd(a) { return a % 2 == 0 };
和
function isOdd(aaa) { return aaa % 2 == 0 };
是一样的。
[]是列表,{}是对象。
(e) => {} 与 ({target}) => {}
第一点,本质上是一样的,是 lambda 的语法,参数列表、箭头、方法体。
第一个用括号表示参数列表,是只有一个参数的时候;第二个,如果有多个参数,则可以用数组表示。就是第二个的用法。
为了避免混淆,记住一种就可以了,就是参数列表用括号,多个参数用逗号分隔。参数名称是任意设置的。
第二点,之所以这里可以用 lambda 表达式,是由 addEventListener 决定的,它的第二个参数就是接受一个回调函数,所以即使不用lambda ,定义普通函数,addEventListener回调时也会将 event 事件传给函数的。本质上 Lambda 表达式的参数列表是由真正的调用者传递的,类型与调用者保持一致就可以了。