溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

JavaScript中箭頭函數(shù)與普通函數(shù)的區(qū)別是什么

發(fā)布時間:2021-08-24 17:15:32 來源:億速云 閱讀:112 作者:chen 欄目:開發(fā)技術(shù)

本篇內(nèi)容介紹了“JavaScript中箭頭函數(shù)與普通函數(shù)的區(qū)別是什么”的有關(guān)知識,在實(shí)際案例的操作過程中,不少人都會遇到這樣的困境,接下來就讓小編帶領(lǐng)大家學(xué)習(xí)一下如何處理這些情況吧!希望大家仔細(xì)閱讀,能夠?qū)W有所成!

箭頭函數(shù):

let fun = () => {
    console.log('lalalala');
}

普通函數(shù):

function fun() {
    console.log('lalla');
}

箭頭函數(shù)相當(dāng)于匿名函數(shù),并且簡化了函數(shù)定義。箭頭函數(shù)有兩種格式,一種只包含一個表達(dá)式,連{ ... }和return都省略掉了。還有一種可以包含多條語句,這時候就不能省略{ ... }和return。

箭頭函數(shù)是匿名函數(shù),不能作為構(gòu)造函數(shù),不能使用new

let FunConstructor = () => {
    console.log('lll');
}

let fc = new FunConstructor();

JavaScript中箭頭函數(shù)與普通函數(shù)的區(qū)別是什么

箭頭函數(shù)不綁定arguments,取而代之用rest參數(shù)...解決

function A(a){
  console.log(arguments);
}
A(1,2,3,4,5,8);  //  [1, 2, 3, 4, 5, 8, callee: ?, Symbol(Symbol.iterator): ?]


let B = (b)=>{
  console.log(arguments);
}
B(2,92,32,32);   // Uncaught ReferenceError: arguments is not defined


let C = (...c) => {
  console.log(c);
}
C(3,82,32,11323);  // [3, 82, 32, 11323]

箭頭函數(shù)不綁定this,會捕獲其所在的上下文的this值,作為自己的this值

var obj = {
  a: 10,
  b: () => {
    console.log(this.a); // undefined
    console.log(this); // Window {postMessage: ?, blur: ?, focus: ?, close: ?, frames: Window, …}
  },
  c: function() {
    console.log(this.a); // 10
    console.log(this); // {a: 10, b: ?, c: ?}
  }
}
obj.b(); 
obj.c();
var obj = {
  a: 10,
  b: function(){
    console.log(this.a); //10
  },
  c: function() {
     return ()=>{
           console.log(this.a); //10
     }
  }
}
obj.b(); 
obj.c()();

箭頭函數(shù)通過 call()  或   apply() 方法調(diào)用一個函數(shù)時,只傳入了一個參數(shù),對 this 并沒有影響。

let obj2 = {
    a: 10,
    b: function(n) {
        let f = (n) => n + this.a;
        return f(n);
    },
    c: function(n) {
        let f = (n) => n + this.a;
        let m = {
            a: 20
        };
        return f.call(m,n);
    }
};
console.log(obj2.b(1));  // 11
console.log(obj2.c(1)); // 11

箭頭函數(shù)沒有原型屬性

var a = ()=>{
  return 1;
}

function b(){
  return 2;
}

console.log(a.prototype);  // undefined
console.log(b.prototype);   // {constructor: ?}

箭頭函數(shù)不能當(dāng)做Generator函數(shù),不能使用yield關(guān)鍵字

總結(jié)

  • 箭頭函數(shù)的 this 永遠(yuǎn)指向其上下文的  this ,任何方法都改變不了其指向,如 call() bind()apply()

  • 普通函數(shù)的this指向調(diào)用它的那個對象

“JavaScript中箭頭函數(shù)與普通函數(shù)的區(qū)別是什么”的內(nèi)容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業(yè)相關(guān)的知識可以關(guān)注億速云網(wǎng)站,小編將為大家輸出更多高質(zhì)量的實(shí)用文章!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI