Es6(3) 箭頭函式

2021-09-10 05:03:42 字數 1396 閱讀 3725

什麼是箭頭函式

var materials = [

'hydrogen',

'helium',

'lithium',

'beryllium'

];materials.map(function(material) ); // [8, 6, 7, 9]

materials.map((material) => ); // [8, 6, 7, 9]

materials.map(material => material.length); // [8, 6, 7, 9]

箭頭函式和普通函式的區別:

1:this指向的區別

function person() , 1000);	

}var p = new person();

上例中,計時器內的this指向window,window內沒有定義age屬性,所以會出現輸出nan.

在es6之前我們的處理方式如下:

function person() , 1000);

}

通過將this值分配給封閉的變數,可以解決this問題。

function person(), 1000);

}var p = new person();

2:arguments物件

箭頭函式不繫結arguments 物件。因此,在本示例中,arguments只是引用了封閉作用域內的arguments:

var arguments = [1, 2, 3];

var arr = () => arguments[0];

arr(); // 1

function foo(n)

foo(1); // 2

在大多數情況下,使用剩餘引數是相較使用arguments物件的更好選擇。

function foo(arg) 

foo(1); // 1

function foo(arg1,arg2)

foo(1,2); //2

3:箭頭函式不能做構造器;

箭頭函式不能用作構造器,和 new一起用會丟擲錯誤。

var foo = () => {};

var foo = new foo(); // typeerror: foo is not a constructor

4:箭頭函式沒有prototype屬性

var foo = () => {};

console.log(foo.prototype); // undefined

es6 3 正則擴充套件

在 es5 中正則使用,要麼是兩個引數,要麼是乙個正規表示式引數 es6 中允許使用兩個引數,但是後邊引數的修飾符會覆蓋前邊的正則修飾符,可通過 es6 新增加的 flags 屬性來獲取正則物件修飾符 g 和 y 都是全域性匹配 g 修飾符是從上一次匹配的位置繼續尋找,直到找到匹配的位置開始,不強調...

ES6 3 變數的解構賦值

陣列的解構賦值其實是 左右進行 模式匹配 右側是具體的數值,不是變數!左側的是變數!如果右側是變數形式,需要先計算出具體的數值!let a,b c 1,2 3 a 1 b 2 c 3let a,tail 1,2,3,4,5 a 1,tail 2,3,4,5 let a,b,c 1 a 1 b und...

學習 ES6 3 語言特性 變數的解構賦值

es6 可以按照一定模式從物件和陣列中提取對應值,並賦值給指定的變數 1,陣列 let items 1,2,3 let i,j,k items console.log i i console.log j j console.log k k i 1,j 2,k 3 let l,m items cons...