生活随笔
收集整理的這篇文章主要介紹了
js箭头函数和普通函数区别
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
js箭頭函數和普通函數區別
實驗環境:nodejs v12.16.1
箭頭函數不能作為構造函數,而普通函數可以
箭頭函數沒有原型,而普通函數有
箭頭函數return可以省略語句塊。(如果=>右邊不是語句塊,則代表return右邊的表達式或對象)
箭頭函數不綁定arguments(注意:瀏覽器環境下獲取箭頭函數的arguments會報錯),而普通函數argument綁定了參數列表對象
this指向問題[重點,也是難點]
- 箭頭函數的this指向上層函數作用域的this對象,如果沒有上層函數作用域,則指向頂部this(在瀏覽器中頂部this則是window)。普通函數的this指向該函數的調用者。
- call, apply, bind會改變普通函數的this,但不會改變箭頭函數的this
實踐是檢驗真理的有效標準,在此,我們必須更加深入了解,再耐心看一個復雜的例子:
依然是nodejs環境下:
data = 40;
this.data = 30;
let pig = {data: 80,
};
let o = {data: 10,a(n) {let f = (n) => {return n + this.data;};return f(n);},b(n) {let f = (n) => {return n + this.data;};let other = {data: 20,};return f.call(other, n);},c(n) {let f = function (n) {return n + this.data;};let other = {data: 20,};return f.call(other, n);},d: (n) => {let f = (n) => {return n + this.data;};return f(n);},e(n) {let f = function (n) {return n + this.data;};let other = {data: 20,};let g = f.bind(other);return g(n);},e1(n) {let f = function (n) {return n + this.data;};return f(n);},e2(n) {let f = (n) => {return n + this.data;};let other = {data: 20,};let g = f.bind(other);return g(n);},
};console.log(o.a(1));
console.log(o.b(1));
console.log(o.c(1));
console.log(o.d(1));
console.log(o.e(1));
console.log(o.e1(1));
console.log(o.e2(1)); console.log(`============接下來比較復雜,但是要搞清楚=========================`);
console.log(o.a.call(pig, 1)); console.log(o.b.call(pig, 1)); console.log(o.c.call(pig, 1)); console.log(o.d.call(pig, 1)); console.log(o.e.call(pig, 1)); console.log(o.e1.call(pig, 1));
console.log(o.e2.call(pig, 1));
箭頭函數內不能用yield且不能用作Generator函數,而普通函數可以。
總結
以上是生活随笔為你收集整理的js箭头函数和普通函数区别的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。