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

1.寫法不同
// function的寫法
function fn(a, b){
return a+b;
}// 箭頭函數(shù)的寫法
let foo = (a, b) =>{ return a + b }2.this的指向不同
在function中,this指向的是調(diào)用該函數(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(); //Windowfunction 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: 03.箭頭函數(shù)不可以當構(gòu)造函數(shù)//使用function方法定義構(gòu)造函數(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存在變量提升,可以定義在調(diào)用語句后;
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() {}關(guān)于ES6箭頭函數(shù)與function區(qū)別是什么就分享到這里了,當然并不止以上和大家分析的辦法,不過小編可以保證其準確性是絕對沒問題的。希望以上內(nèi)容可以對大家有一定的參考價值,可以學以致用。如果喜歡本篇文章,不妨把它分享出去讓更多的人看到。
本文標題:ES6箭頭函數(shù)與function區(qū)別是什么?-創(chuàng)新互聯(lián)
網(wǎng)頁地址:http://chinadenli.net/article44/dphihe.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供Google、外貿(mào)網(wǎng)站建設(shè)、網(wǎng)頁設(shè)計公司、關(guān)鍵詞優(yōu)化、域名注冊、網(wǎng)站維護
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容