箭头函数
胖大人本胖
共 746 字
预计
8
分钟
定义
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| const fn = () => { return '渡远荆门外'; }; console.log(fn());
const fn1 = str => { return str; }; console.log(fn1('渡远荆门外'));
const fn2 = (str1, str2, str3) => { return `${str1} ${str2} ${str3}`; } console.log(fn2('渡远荆门外','来从楚国游','山随平野尽'));
|
函数内部无逻辑,直接返回的,省略大括号
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| const fn = () => '渡远荆门外'; console.log(fn());
const fn1 = str => str; console.log(fn1('渡远荆门外'));
const fn3 = str => console.log(str); fn3('山随平野尽');
const fn4 = () => fn1('月涌大荒流'); fn4();
const fn2 = (str1, str2, str3) => `${str1} ${str2} ${str3}`; console.log(fn2('渡远荆门外','来从楚国游','山随平野尽'));
|
关于this指向
- funtion 定义函数时this指向是运行时决定的;箭头函数的指向时编译时决定的
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
| <template> <div class="container"> <button @click="handleClick"> {{btnText}} </button> </div> </template> <script> import { MessageBox } from 'element-ui'; export default { data() { return { btnText: '提交', }; }, methods: { handleClick() { MessageBox({ title: '弹窗标题', message: '弹窗消息祝内容', type: 'success', callback: (action, instance) => { this.btnText = '提交中'; // 箭头函数的this是继承下来的指向的是组件实例 } }) }, handleClickFn() { const self = this; MessageBox({ title: '弹窗标题', message: '弹窗消息祝内容', type: 'success', callback: function(action, instance) { self.btnText = '提交中'; // 如果使用的是function定义函数,必须提前定义this } }) } }, } </script>
|
箭头函数的解构
1 2 3 4 5 6 7 8 9 10 11
| const params = { name: '李白', isDie: true, } const getName = params => params; const friends = [params, '小白', getName];
const fn = ([{name, isDie},,fn],fn2) => { console.log(name,fn(name), fn2(isDie)) } fn(friends,getName);
|
对象属性是函数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| const people = { name: '李白', getAge() { console.log(this.name); return 18; } }
const people = { name: '李白', getAge: function () { console.log(this.name); return 18; } }
const people = { name: '李白', getAge: () => { console.log(this.name); return 18; } }
|