函數的擴展
1函數的參數指定默認值
ES6 之前,不能直接爲函數的參數指定默認值,只能採用變通的方法
ES6 允許爲函數的參數設置默認值,即直接寫在參數定義的後面。
function log(x, y = 'World') {
console.log(x, y);
}
log('Hello') // Hello World
log('Hello', 'China') // Hello China
log('Hello', '') // Hello
參數變量是默認聲明的,所以不能用let
或const
再次聲明。
使用參數默認值時,函數不能有同名參數,否則就報錯
2參數默認值可以與解構賦值的默認值,結合起來使用。
function foo({x, y = 5}) {
console.log(x, y);
}
foo({}) // undefined 5
foo({x: 1}) // 1 5
foo({x: 1, y: 2}) // 1 2
指定了默認值以後,函數的length
屬性,將返回沒有指定默認值的參數個數。也就是說,指定了默認值後,length
屬性將失真。
3.函數的name
屬性,返回該函數的函數名。
function foo() {}
foo.name // "foo"
4.ES6 允許使用“箭頭”(=>
)定義函數。
var f = v => v;
// 等同於
var f = function (v) {
return v;
};
//例2
const add1 = (a, b) => {
a += 1;
return a + b;
};
const add2 = function(a, b) {
a += 1;
return a + b;
}
console.log(add1(2, 2));
console.log(add2(2, 2));
//5 5
如果箭頭函數不需要參數或需要多個參數,就使用一個圓括號代表參數部分。
var f = () => 5;
// 等同於
var f = function () { return 5 };
如果箭頭函數的代碼塊部分多於一條語句,就要使用大括號將它們括起來,並且使用return
語句返回。
var sum = (num1, num2) => { return num1 + num2; }
由於大括號被解釋爲代碼塊,所以如果箭頭函數直接返回一個對象,必須在對象外面加上括號,否則會報錯。
let getTempItem = id => ({ id: id, name: "Temp" });
如果箭頭函數只有一行語句,且不需要返回值,可以採用下面的寫法,就不用寫大括號了。
let fn = () => void doesNotReturn();
用...args代替argument取參的方式
const log = (...args) => {
console.log(args);
};
log(1, 2, 3);
箭頭函數沒有自己的this,它的this是所處函數環境當中的this
const xiaoming = {
name: 'xiaoming',
say1: function() {
console.log(this);
},
say2: () => {
console.log(this);
}
}
xiaoming.say1();
xiaoming.say2();
const xiaoming = {
name: 'xiaoming',
age: null,
getAge: function() {
//保留this的方式
let _this = this;
// ...ajax
setTimeout(function() {
//通過閉包的特性拿到this
_this.age = 14;
console.log(_this);
}, 1000);
}
};
//箭頭函數寫法
const xiaoming = {
name: 'xiaoming',
age: null,
getAge: function() {
// ...ajax
setTimeout(() => {
this.age = 14;
console.log(this);
}, 1000);
}
};
xiaoming.getAge();
編程實戰:
知識點:splice() 方法向/從數組中添加/刪除項目,然後返回被刪除的項目。註釋:該方法會改變原始數組
arrayObject.splice(index,howmany,item1,.....,itemX)
index 必需。整數,規定添加/刪除項目的位置,使用負數可從數組結尾處規定位置。
howmany 必需。要刪除的項目數量。如果設置爲 0,則不會刪除項目。
item1,..itemx 可選。向數組添加的新項目。
function insert(value) {
return {
into: (array) => {
return {
after: (afterValue) => {
array.splice(array.indexOf(afterValue) + 1, 0, value);
return array;
}
};
}
};
}
console.log(insert(2).into([1, 3]).after(1))
//[1,2,3]
//或者如下簡潔寫法
function insert(value) {
return {
into(array) {
return {
after(afterValue) {
array.splice(array.indexOf(afterValue) + 1, 0, value);
return array;
}
};
}
};
}
console.log(insert(2).into([1, 3]).after(1))