欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

JavaScript中箭頭函數(shù)與普通函數(shù)的區(qū)別詳解

 更新時(shí)間:2021年08月24日 14:17:03   作者:biubiu小希希  
這篇文章主要介紹了JavaScript中箭頭函數(shù)與普通函數(shù)的區(qū)別,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下

本文為大家講解了JavaScript中箭頭函數(shù)與普通函數(shù)的區(qū)別,供大家參考,具體內(nèi)容如下

箭頭函數(shù):

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

普通函數(shù):

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

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

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

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

let fc = new FunConstructor();

箭頭函數(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,會(huì)捕獲其所在的上下文的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)用一個(gè)函數(shù)時(shí),只傳入了一個(gè)參數(shù),對(duì) 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)用它的那個(gè)對(duì)象

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論