ES6---箭头函数()={} 与function的区别(转载)
生活随笔
收集整理的這篇文章主要介紹了
ES6---箭头函数()={} 与function的区别(转载)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1.箭頭函數與function定義函數的寫法:
//function function fn(a, b){return a + b; } //arrow function var foo = (a, b)=>{ return a + b };2.this的指向:
使用function定義的函數,this的指向隨著調用環境的變化而變化的,而箭頭函數中的this指向是固定不變的,一直指向的是定義函數的環境。
//使用function定義的函數 function foo(){console.log(this); } var obj = { aa: foo }; foo(); //Window obj.aa() //obj { aa: foo }使用function定義的函數中this指向是隨著調用環境的變化而變化的
//使用箭頭函數定義函數 var foo = () => { console.log(this) }; var obj = { aa:foo }; foo(); //Window obj.aa(); //Window明顯使用箭頭函數的時候,this的指向是沒有發生變化的。
3.構造函數
//使用function方法定義構造函數 function Person(name, age){this.name = name;this.age = age; } var lenhart = new Person(lenhart, 25); console.log(lenhart); //{name: 'lenhart', age: 25} //嘗試使用箭頭函數 var Person = (name, age) =>{this.name = name;this.age = age; }; var lenhart = new Person('lenhart', 25); //Uncaught TypeError: Person is not a constructorfunction是可以定義構造函數的,而箭頭函數是不行的。
4.變量提升
由于js的內存機制,function的級別最高,而用箭頭函數定義函數的時候,需要var(let const定義的時候更不必說)關鍵詞,而var所定義的變量不能得到變量提升,故箭頭函數一定要定義于調用之前!
foo(); //123 function foo(){console.log('123'); }arrowFn(); //Uncaught TypeError: arrowFn is not a function var arrowFn = () => {console.log('456'); };?
轉載于:https://www.cnblogs.com/ysx215/p/10774789.html
總結
以上是生活随笔為你收集整理的ES6---箭头函数()={} 与function的区别(转载)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 迭代之嵌套的for循环
- 下一篇: poj 2891 Strange Way