ES6學習筆記函式的擴充套件(函式的預設值)

2021-09-11 03:36:43 字數 2655 閱讀 8968

一、函式引數的預設值

1.es6 之前,不能直接為函式的引數指定預設值,只能採用變通的方法。例如

function

log(x,y)

log(

'hello');

//hello world

log(

'hello'

,'china');

//hello china

log(

'hello',''

);//hello world

2.es6 允許為函式的引數設定預設值,即直接寫在引數定義的後面。

function

log(x, y =

'world'

)log

('hello'

)// hello world

log(

'hello'

,'china'

)// hello china

log(

'hello',''

)// hello

3.引數變數是預設宣告的,所以不能用let或const再次宣告。

function

foo(x =5)

4.使用引數預設值時,函式不能有同名引數。

// 不報錯

function

foo(x, x, y)

// 報錯

function

foo(x, x, y =1)

// syntaxerror: duplicate parameter name not allowed in this context

二、與解構賦值預設值結合使用

引數預設值可以與解構賦值的預設值,結合起來使用。

function

foo(

)foo()

//undefined 5

foo(

)// 1 5

foo(

)// 1 2

foo(

)// typeerror: cannot read property 'x' of undefined

如果沒有提供引數,函式foo的引數默乙個空物件,不然會報錯

//1

function

foo(=)

foo(

)// undefined 5

//2function

fetch

(url,})

fetch

('',)

// "get"

fetch

('')//3

function

fetch

(url,}=

)fetch

('')// "get"

三、函式的length屬性

指定了預設值以後,函式的length屬性,將返回沒有指定預設值的引數個數。也就是說,指定了預設值後,length屬性將失真。

(

function

(a))

.length //1

(function

(a =5)

).length // 0

(function

(a, b, c =5)

).length // 2

如果設定了預設值的引數不是尾引數,那麼length屬性也不再計入後面的引數了。

(

function

(a =

0, b, c)

).length // 0

(function

(a, b =

1, c)

).length // 1

四、作用域

設定了引數的預設值,函式進行宣告初始化時,引數會形成乙個單獨的作用域,在不設定引數預設值時,是不會出現的。

//指向第乙個x的引數

var x =1;

function

f(x,y=x)f(

2)//2

//指向外層的x

let x =1;

function

f(y = x)f(

)// 1

//如果此時x沒有定義就會報錯

function

f(y = x)f(

)// referenceerror: x is not defined

//不容易發現的暫時性死區

var x =1;

function

foo(x = x)

foo(

)// referenceerror: x is not defined

//引數再預設宣告的時候(let x = x) 會形成暫時性死區

利用引數預設值,可以指定某乙個引數不得省略,如果省略就丟擲乙個錯誤。

function

throws()

function

foo(parameters=

throw()

)foo()

// error: 缺少引數

ES6學習筆記(函式擴充套件)

1.預設引數function people people 輸出 3 30 people 輸出 undefined 302.擴充套件運算子 剩餘引數 在es6之前,如果要在方法內將多字符集成為乙個陣列,一般會使用以下寫法 function sum sum 1,2,123,qwer es6之後,使用運算...

ES6學習筆記九 函式的擴充套件

一 函式引數的預設值function log x,y world log hello hello world log hello hello注意 引數是預設宣告的,所以在函式體內不能用let或const再次宣告 function foo x 5 注意 使用引數預設值時,函式不能有同名引數 funct...

ES6 函式的擴充套件

在es5中有這種情況 function fn a,b fn 30 fn 0,10 20因為a 0,所以將10賦給它在es6中 function fn a 10,b 20 fn 30 fn 0,10 10rest 引數形式為 變數名 用於獲取函式的多餘引數,這樣就不需要使用arguments物件了。r...