Vue ES6箭头函数使用总结

Vue ES6箭头函数使用总结

 

by:授客 QQ1033553122

 

 

箭头函数

 

ES6允许使用“箭头”(=>)定义函数:

 

函数不带参数

定义方法:函数名称 = () => 函数体

let func = () => 1

 

等同于

function func() {

return 1;

}

 

函数只带一个参数

定义方法:

函数名称 = 参数 => 函数体

或者

函数名称 = (参数) => 函数体

 

 

let func = state => state.count

 

等同于

function func(state) {

return state.count;

}

 

 

函数带多个参数

定义方法:函数名称 = (参数1,参数2,...,参数N) =>函数体

 

let arg2 = 1

let func = (state, arg2) => state.count + arg2

 

等同于

function func(state,arg2) {

return state.count + arg2;

}

 

函数体包含多条语句

let author = {

    name: "授客",

    age: 30,

viewName: () => {

        console.log("author name"); // 输出undefined

        // 当前this指向了定义时所在的对象

        console.log(this.name); // 输出undefined,并没有得到"授客"

    }

};

 

author.viewName();

 

注意

函数体内的this对象,就是定义时所在的对象,而不是使用它时所在的对象

 

 

猜你喜欢

转载自www.cnblogs.com/shouke/p/12039600.html
今日推荐