1. ES6的對象屬性增強型寫法
ES6以前定義一個對象
const name = "zzz";
const age = 18;
const user = {
name:name,
age:age
}
console.log(user);
ES6寫法
const name = "zzz";
const age = 18;
const user = {
name,age
}
console.log(user);
2 ES6對象的函數增強型寫法
ES6之前對象內定義函數
const obj = {
run:function(){
console.log("奔跑");
}
}
ES6寫法
const obj = {
run(){
console.log("奔跑");
}
}
3. 箭頭函數
傳統定義函數的方式
const aaa = function (param) {
}
對象字面量中定義函數
const obj = {
bbb (param) { },
}
ES6中的箭頭函數
//const ccc = (參數列表) => {}
const ccc = () => {}
4. 箭頭函數的參數和返回值
4.1 參數問題
1.放入兩個參數
const sum = (num1,num2) => {
return num1 + num2
}
2.放入一個參數,()可以省略
const power = num => {
return num * num
}
4.2 函數內部
1.函數中代碼塊中有多行代碼
const test = () =>{
console.log("hello zzz")
console.log("hello vue")
}
2.函數代碼塊中只有一行代碼,可以省略return
// const mul = (num1,num2) => {
// return num1 * num2
// }
const mul = (num1,num2) => num1* num2
// const log = () => {
// console.log("log")
// }
const log = () => console.log("log")
4.3 箭頭函數的this使用
什么時候使用箭頭函數
setTimeout(function () {
console.log(this)
} , 1000);
setTimeout(() => {
console.log(this)//這里this找的是window的this
}, 1000);
結論:箭頭函數沒有this,這里this引用的是最近作用域(aaa函數里的this)的this。
const obj = {
aaa(){
setTimeout(function () {
console.log(this)//window
});
setTimeout(() => {
console.log(this)//obj
});
}
}
obj.aaa()
上述中第一個是window對象的this,第二個箭頭函數的this是obj的。
const obj = {
aaa() {
setTimeout(function () {
setTimeout(function () {
console.log(this) //window
})
setTimeout(() => {
console.log(this) //window
})
})
setTimeout(() => {
setTimeout(function () {
console.log(this) //window
})
setTimeout(() => {
console.log(this) //obj
})
})
}
}
obj.aaa()
