1.函数
1.1函数默认值
es5:
function add(a,b){
a = a || 10;
b = b || 20;
return a + b
}
es6:
function add(a=10, b=20){
return a + b
}
1.2函数默认表达式可以是一个函数
function add(a, b=getVal(5)){
return a + b
}
function getVal(val){
return val + 1
}
add(20)
1.3剩余运算符...
剩余参数是数组,真实的数组,arguments
是伪数组
剩余参数必须放在后面
function pick(obj, ...keys){
console.log(keys) //keys是数组,真实的数组,arguments是伪数组
}
let book = {
title:'es',
author:'xs',
year:33
}
1.4扩展运算符...
将一个数组分割,并将各个项作为分离的参数传给函数
//求最大值:Math.max(10,20)
ES5:
const arr = [10,20,30,40,80,78,95,1000]
console.log(Math.max.apply(null, arr))
ES6:
console.log(Math.max(...arr))
1.5箭头函数
let add = function(a, b){
return a + b
}
箭头函数
let add = (a, b) => {
return a + b
}
let f = v=>v;
//等同于
let f = function(v){
return v;
}
// 有一个参数
let add = value => value;
// 有两个参数
let add = (value,value2) => value + value2;
let add = (value1,value2)=>{
return value1 + value2;
}
// 无参数
let fn = () => "hello world";
let doSomething = () => {
}
//如果箭头函数直接返回一个对象,必须在对象外面加上括号,否则会报错。
let getId = id => ({id: id,name: 'mjj'}) //注意
let obj = getId(1);
1.5.1箭头函数指向
如果箭头函数被一个非箭头函数所包括,那么this的值与该函数的所属对象相等,否则 则是全局的window对象
let PageHandler = {
id:123,
init:function(){
document.addEventListener('click',function(event) {
this.doSomeThings(event.type);
},false);
},
doSomeThings:function(type){
console.log(`事件类型:${type},当前id:${this.id}`);
}
}
PageHandler.init();
//解决this指向问题
// 方法1: bind
let PageHandler = {
id: 123,
init: function () {
// 使用bind来改变内部函数this的指向
document.addEventListener('click', function (event) {
this.doSomeThings(event.type);
}.bind(this), false);
},
doSomeThings: function (type) {
console.log(`事件类型:${type},当前id:${this.id}`);
}
}
PageHandler.init();
//方法2:
let PageHandler = {
id: 123,
init: function () {
// 箭头函数没有this的指向,箭头函数内部的this值只能通过查找作用域链来确定
// 如果箭头函数被一个非箭头函数所包括,那么this的值与该函数的所属对象相等,
//否则 则是全局的window对象
document.addEventListener('click', (event) => {
console.log(this);
this.doSomeThings(event.type);
}, false);
},
doSomeThings: function (type) {
console.log(`事件类型:${type},当前id:${this.id}`);
}
}
PageHandler.init();
1.5.2注意事项
箭头函数中没有arguments对象
var getVal = (a,b) => {
console.log(arguments);
return a + b;
}
console.log(getVal(1,2)); //arguments is not defined
箭头函数不能使用new关键字来实例化对象
let Person = ()=>{}
let p1 = new Person();// Person is not a constructor
箭头函数是一个语法塘,他是表达式不是对象,所以没有constructor
属性,所以不能用new
来实例化