ES6箭頭函數(shù)與function區(qū)別是什么?-創(chuàng)新互聯(lián)

今天小編給大家分享的是ES6箭頭函數(shù)與function區(qū)別是什么?很多人都不太了解,今天小編為了讓大家更加了解,所以給大家總結了以下內(nèi)容,一起往下看吧。一定會有所收獲的哦。

站在用戶的角度思考問題,與客戶深入溝通,找到鎮(zhèn)江網(wǎng)站設計與鎮(zhèn)江網(wǎng)站推廣的解決方案,憑借多年的經(jīng)驗,讓設計與互聯(lián)網(wǎng)技術結合,創(chuàng)造個性化、用戶體驗好的作品,建站類型包括:成都做網(wǎng)站、網(wǎng)站設計、企業(yè)官網(wǎng)、英文網(wǎng)站、手機端網(wǎng)站、網(wǎng)站推廣、域名與空間、虛擬空間、企業(yè)郵箱。業(yè)務覆蓋鎮(zhèn)江地區(qū)。

1.寫法不同

// function的寫法
function fn(a, b){
    return a+b;
}
// 箭頭函數(shù)的寫法
let foo = (a, b) =>{ return a + b }

2.this的指向不同

在function中,this指向的是調用該函數(shù)的對象;

//使用function定義的函數(shù)
function foo(){
    console.log(this);
}
var obj = { aa: foo };
foo(); //Window
obj.aa() //obj { aa: foo }

而在箭頭函數(shù)中,this永遠指向定義函數(shù)的環(huán)境。

//使用箭頭函數(shù)定義函數(shù)
var foo = () => { console.log(this) };
var obj = { aa:foo };
foo(); //Window
obj.aa(); //Window
function Timer() {
  this.s1 = 0;
  this.s2 = 0;
  // 箭頭函數(shù)
  setInterval(() => {
     this.s1++;
     console.log(this);
  }, 1000); // 這里的this指向timer
  // 普通函數(shù)
  setInterval(function () {
    console.log(this);
    this.s2++; // 這里的this指向window的this
  }, 1000);
}

var timer = new Timer();

setTimeout(() => console.log('s1: ', timer.s1), 3100);
setTimeout(() => console.log('s2: ', timer.s2), 3100);
// s1: 3
// s2: 0
3.箭頭函數(shù)不可以當構造函數(shù)
//使用function方法定義構造函數(shù)
function Person(name, age){
    this.name = name;
    this.age = age;
}
var lenhart =  new Person(lenhart, 25);
console.log(lenhart); //{name: 'lenhart', age: 25}
//嘗試使用箭頭函數(shù)
var Person = (name, age) =>{
    this.name = name;
    this.age = age;
};
var lenhart = new Person('lenhart', 25); //Uncaught TypeError: Person is not a constructor

另外,由于箭頭函數(shù)沒有自己的this,所以當然也就不能用call()、apply()、bind()這些方法去改變this的指向。

4.變量提升

function存在變量提升,可以定義在調用語句后;

foo(); //123
function foo(){
    console.log('123');
}

箭頭函數(shù)以字面量形式賦值,是不存在變量提升的;

arrowFn(); //Uncaught TypeError: arrowFn is not a function
var arrowFn = () => {
    console.log('456');
};
console.log(f1); //function f1() {}   
console.log(f2); //undefined  
function f1() {}
var f2 = function() {}

關于ES6箭頭函數(shù)與function區(qū)別是什么就分享到這里了,當然并不止以上和大家分析的辦法,不過小編可以保證其準確性是絕對沒問題的。希望以上內(nèi)容可以對大家有一定的參考價值,可以學以致用。如果喜歡本篇文章,不妨把它分享出去讓更多的人看到。

本文標題:ES6箭頭函數(shù)與function區(qū)別是什么?-創(chuàng)新互聯(lián)
網(wǎng)頁地址:http://muchs.cn/article44/dphihe.html

成都網(wǎng)站建設公司_創(chuàng)新互聯(lián),為您提供Google、外貿(mào)網(wǎng)站建設、網(wǎng)頁設計公司、關鍵詞優(yōu)化、域名注冊、網(wǎng)站維護

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉載內(nèi)容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉載,或轉載時需注明來源: 創(chuàng)新互聯(lián)

外貿(mào)網(wǎng)站制作