一、ES6可以直接在大括号里面直接写入变量和函数,作为对象的属性和方法
let ad = document.getElementById('event')
let name = "tom"
let change = function() {
console.log(1)
}
const school = {
name,
change,
improve() {
// 在ES6中,:function可以省略
console.log(2)
}
}
console.log(school.name, school.change);
二、箭头函数
例如:
ad.addEventListener("click", function() {
console.log(this)
let _this = this
setTimeout(function() {
console.log(this)
console.log(_this)
}, 2000)
}, false)
在上面的这个this中,是调用的window里面的this,而不是这个当前的函数块里的this,在setTimeout函数里面的this为window里的,要先在外面将this给保存下来:
let _this = this,然后再获取
箭头函数不需要写函数名:可以简写函数;上面的函数可以改写成:
例如:
ad.addEventListener("click", function() {
setTimeout(() => {
console.log(this)
}, 2000);
}, false)
不需要将this保存即可使用,所以综上:
箭头函数适合与this无关的回调,定时器和数组的有关操作
箭头函数不适合与this的有关回调,事件回调和有关方法,只是不适合,不是不可以
箭头函数(ES6的新特性)箭头函数有返回值
原生函数的this指向他的调用者,如果没有则指向window
箭头函数的this指向的是他的定义者,而不是使用时的对象
箭头函数的this先在其作用域中找,如果没有,再往上找,直到找到为止
箭头函数不能作为构造实例化对象
省略花括号时,return也要省略
例如:
const arr = [1, 25, 32, 65, 87, 9, 5, 6, 8, 96]
const result = arr.filter(function(item) {
if (item % 2 == 0) {
return true;
} else {
return false;
}
});
// console.log(result)
// 使用箭头函数可以简写
const result1 = arr.filter(item2 => //arr.filter()对数组进行一个筛选
item2 % 2 == 0 //如果只有一条函数,其花括号和return都要省略
);
console.log(result);
console.log(result1);
以上为函数在ES6中的新特性和使用方法,希望对你有所帮助