1.默認參數
function fn(name,age=17){
console.log(name+","+age);
}
fn("Amy",18); // Amy,18
fn("Amy",""); // Amy,
fn("Amy"); // Amy,17
es6之前想要指定默認參數
if (typeof y === 'undefined') {
y = 'World';
}
參數變量是默認聲明的,所以不能用let或const再次聲明。
function foo(x = 5) {
let x = 1; // error
const x = 2; // error
}
使用參數默認值時,函數不能有同名參數。
// 不報錯
function fn(name,name){
console.log(name);
}
// 報錯
//SyntaxError: Duplicate parameter name not allowed in this context
function fn(name,name,age=17){
console.log(name+","+age);
}
,參數默認值不是傳值的,而是每次都重新計算默認值表達式的值。也就是說,參數默認值是惰性求值的。
let x = 99;
function foo(p = x + 1) {
console.log(p);
}
foo() // 100
x = 100;
foo() // 101
如果非尾部的參數設置默認值,實際上這個參數是沒法省略的。
想要使參數等於默認值,除非顯式輸入undefined
function f(x, y = 5, z) {
return [x, y, z];
}
f(1, ,2) // 報錯
f(1, undefined, 2) // [1, 5, 2]
2.箭頭函數
var f = (v) => {
return v;
};
//可簡寫爲
var f = v => v;
// 等同於
var f = function (v) {
return v;
};
(1)函數體內的this對象,就是定義時所在的對象,而不是使用時所在的對象。
由於箭頭函數沒有自己的this,所以當然也就不能用call()、apply()、bind()這些方法去改變this的指向。
(2)不可以當作構造函數,也就是說,不可以使用new命令,否則會拋出一個錯誤。
(3)不可以使用arguments對象,該對象在函數體內不存在。如果要用,可以用 rest 參數代替。
(4)不可以使用yield命令,因此箭頭函數不能用作 Generator 函數。*
// 回調函數
var Person = {
'age': 18,
'sayHello': function () {
setTimeout(function () {
console.log(this.age);
});
}
};
var age = 20;
Person.sayHello(); // 20
var Person1 = {
'age': 18,
'sayHello': function () {
setTimeout(()=>{
console.log(this.age);
});
}
};
var age = 20;
Person1.sayHello(); // 18
不使用場合
定義對象的方法,且該方法內部包括this。
const cat = {
lives: 9,
jumps: () => {
this.lives--;
}
}
第二個場合是需要動態this的時候
var button = document.getElementById('press');
button.addEventListener('click', () => {
this.classList.toggle('on');
});