ES5中的闭包
<script>
var btns = document.getElementsByTagName("button");
for (var i = 0; i < btns.length; i++) {
(function (i) {
btns[i].addEventListener('click', function () {
console.log('第' + i + '个按钮被点击');
})
})(i)
}
</script>
ES6中的写法
<script>
const btns = document.getElementsByTagName("button");
for (let i = 0; i < btns.length; i++) {
btns[i].addEventListener('click', function (){
console.log('第' + i + '个按钮被点击');
})
}
</script>
对象增强写法
ES5:
<script>
let name = 'tolerate';
let age = 25;
let height = 1.78;
const person = {
name : name,
age : age,
height : height,
run : function() {
console.log('在跑');
}
}
console.log(person);
person.run();
</script>
ES6:
<script>
let lname = 'tolerate';
let lage = 25;
let lheight = 1.78
const lperson = {
lname,
lage,
lheight,
eat() {
console.log('在吃');
}
}
console.log(lperson);
lperson.eat();
</script>