ES6语法 学习笔记(三)函数变化

参数变化

  • 1.函数默认参数
function show(a='456',b='123'){
    console.log(a,b);
}
show();
//不传参数则打印默认值,如果默认值也没有则是undefined undefined

//也可以穿的是一个对象
function show({x=0,y=0}={}){
    console.log(x,y);
}
show();
  • 2.函数参数默认已经定义了,不能再使用let,const再定义
function show(a=18){
	let a = 101;  //错误
	console.log(a);
}
show();

扩展运算符、Rest运算符(…)

  • 用法简介:
    [1,2,3,4] -> … [1,2,3,4] -> 1 2 3 4,5
    1 2 3 4 5 -> …1 2 3 4 5 -> [1,2,3,4,5]

  • 用法示例

let arr = ['apple','banana','orange'];
console.log(arr);
console.log(...arr);//apple banana orange
  • 在参数上的用法
function show(...a){
    console.log(a);
}
show(1,2,3,4,5);//[1,2,3,4,5]

//也可以反过来使用
function show(a,b,c){
    console.log(a,b,c);
}
show(...[1,9,8]);

箭头函数

//写法
() =>{
    //语句
    //return
}
  • 示例:
//示例1
// function show(){
//     return 1;
// }
// console.log(show());
let show = ()=>1;
console.log(show());

//示例2
/* function show(a,b){
    return a+b;
}
console.log(show(12,5)); */
let show = (a,b)=>a+b;
console.log(show(12,5));

//示例3
let show=(a=12,b=5)=>{
    console.log(a,b);
    return a+b;
};
show();
  • 箭头函数this的指向
var id = 10;  //用var定义一个全局变量,属于window, let,const不同
let json={
    show:function(){
        setTimeout(()=>{
            alert(this.id);
        },2000);
    }
};
json.show();//结果为undefined

箭头函数中的this指向的是定义函数(show)所在的对象(json中),json中没有id所以为undefined

  • 注意事项
    1.箭头函数里面没有arguments, 用 ‘…’
    2.箭头函数不能当构造函数
/* function show(){
    this.name='abc';
} */
let show = ()=>{
    this.name='abc';
}
let s=new show();
alert(s.name);
//Uncaught TypeError: show is not a constructor
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

boboj1

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值