一、ES6箭头(=>)函数
//声明一个函数
let fn = (a,b) => {
return a+b;
}
//调用函数
let result = fn(1 + 2);
console.log(result);
1.this是静态的,this始终指向函数声明时所在作用域下的this的值
function getName(){
console.log(this.name);
}
let getName2 = () => {
console.log(this.name);
}
//设置window对象的name属性
window.name = 'TNT';
const stars = {
name:"时代少年团"
}
//直接调用
getName();
getName2();
//call 方法调用
getName.call(stars);
getName2.call(stars);
//直接调用
//call方法调用
2.不能作为构造实例化对象
let Person = (name,age) => {
this.name = name;
this.age = age;
}
let song = new Person('宋亚轩',18);
console.log(song);
3.不能使用 arguments 变量存放实参
let fn = () => {
console.log(arguments);
}
fn(1,2,3);
4.箭头函数的简写
(1)省略小括号,当形参有且只有一个的时候
let add = n => {
return n + n;
}
console.log(add(9));
(2)省略花括号,当代码体只有一条语句的时候,此时return必须省略,而且语句的执行结果就是函数的返回值
let sum = n => n+n;
console.log(sum(9));
箭头函数适合与this无关的回调. 定时器,数组的方法回调
箭头函数 不适合与this有关的回调. 事件回调,对象的方法
二、函数参数赋值初始值
1.形参初始值 具有默认值的参数,一般位置要靠后
//三个形参对应三个实参
function add(a,b,c = 10) {//形参c有默认值
return a + b + c;
}
let result = add(1,2);
console.log(result);
//假若有默认值的形参位置没有靠后
function add(a,c = 10,b) {//形参c有默认值
return a + b + c;
}
let result = add(1,2);
console.log(result);
若有默认值的形参没有靠后,则会返回NaN
2.与解构赋值结合
function connect({host:"时团",username,password,port}){
console.log(host);
console.log(username);
console.log(password);
console.log(port);
}
connect({
host:'sdfj',
username:'小宋',
password: 'zyh',
port: 3360
})
三、rest参数
ES6引入rest参数 用于获取函数的实参,用来替代arguments
1.ES5 获取实参的方式
function remember() {
console.log(arguments);
}
remember('马嘉祺','丁程鑫','宋亚轩','刘耀文','张真源','严浩翔','贺峻霖');
2.rest参数
function remember(...args){
console.log(args);// filter some every map
}
remember('马嘉祺','丁程鑫','宋亚轩','刘耀文','张真源','严浩翔','贺峻霖');
3.rest参数必须要放到参数最后
function fn(a,b,...args){
console.log(a);
console.log(b);
console.log(...args);
}
fn(1,2,3,4,5,6);