ES6函式擴充套件

2021-10-01 23:27:15 字數 3353 閱讀 2410

rest

嚴格模式

箭頭函式

尾呼叫

//方式一

//問題:對應的布林值為false,則該賦值不起作用

function log

(x, y)

log(

'hello'

)// hello world

log(

'hello'

,'china'

)// hello china

log(

'hello',''

)// hello world

//方式二

function log

(x, y)

console.

log(x, y);}

log(

'hello'

)// hello world

log(

'hello'

,'china'

)// hello china

log(

'hello',''

)// hello world

//es6的寫法

function log

(x, y =

'world'

)log

('hello'

)// hello world

log(

'hello'

,'china'

)// hello china

log(

'hello',''

)// hello

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

function foo

(x =5)

// 寫法一

function m1(=

)// 寫法二

function m2(=

)// 函式沒有引數的情況m1(

)// [0, 0]m2(

)// [0, 0]

// x 和 y 都有值的情況m1(

)// [3, 8]m2(

)// [3, 8]

// x 有值,y 無值的情況m1(

)// [3, 0]m2(

)// [3, undefined]

// x 和 y 都無值的情況m1(

)// [0, 0];m2(

)// [undefined, undefined]m1(

)// [0, 0]m2(

)// [undefined, undefined]

function f

(x =

1, y)f(

1,,2

)// 報錯

//有預設值的引數都不是尾引數。需要顯式輸入undefined。

返回沒有指定預設值的引數個數

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

(

function(.

..args)

).length // 0

(function (a =

0, b, c)

).length // 0

引數會形成乙個單獨的作用域(context)。等到初始化結束,這個作用域就會消失。

var x =1;

function foo

(x = x)

foo(

)// referenceerror: x is not defined

//數x = x形成乙個單獨作用域。實際執行的是let x = x,由於暫時性死區的原因,這行**會報錯」x 未定義「。

var x =1;

function foo

(x, y =

function()

)foo()

// 3

x // 1

var x =1;

function foo

(x, y =

function()

)foo()

// 2

x // 1

數之後不能再有其他引數(即只能是最後乙個引數),否則會報錯。

// 報錯

function f

(a,.

..b, c)

函式引數使用了預設值、解構賦值、或者擴充套件運算子,那麼函式內部就不能顯式設定為嚴格模式

// 預設值 報錯 

function dosomething

(a, b = a)

// 解構賦值 報錯

const dosomething = function ();

// 擴充套件運算子 報錯

const dosomething =(.

..a)

=>

;const obj =)}

;

只有從函式體之中,才能知道引數是否應該以嚴格模式執行,但是引數卻應該先於函式體執行。

規避這種限制

'use strict'

;function dosomething

(a, b = a)

const dosomething =

(function ();

}())

;

var f = v =

> v;

// 等同於

var f = function (v)

;

(1)函式體內的this物件,就是定義時所在的物件,而不是使用時所在的物件。

(2)不可以當作建構函式,也就是說,不可以使用new命令,否則會丟擲乙個錯誤。

(3)不可以使用arguments物件,該物件在函式體內不存在。如果要用,可以用 rest 引數代替。

(4)不可以使用yield命令,因此箭頭函式不能用作 generator 函式。

指某個函式的最後一步是呼叫另乙個函式。

尾呼叫,可以做到每次執行時,呼叫幀只有一項,這將大大節省記憶體。

function f

(x)

ES6 函式擴充套件

函式在js裡是相當重要的一部分了,es6裡也新增了一些函式方法,來看一下 test hello hello world test hello kill hello kill es6增加了函式引數預設值,可以直接在宣告引數的同時賦預設值,但是也可以後面重新賦值 test2 kill 括號內有引數x時,...

ES6函式擴充套件

函式引數的預設值 在es5中,我們想給函式乙個預設值,需要這樣寫 function add x,y 在es6中 可以這樣寫 function add x,y ss add dd ddss add ss dd ssdd add dd dd我們只需要在引數上直接寫上我們想要的預設值就好了。當我們給函式乙...

ES6函式擴充套件

function fun a,b world fun hello 輸出helloworld let a aa function fun a,b a fun bb function fun arg fun 1,2,3,4,1 語法 param param 對應函式 function 沒有引數 乙個引數...