JavaScript中箭頭函數(shù)與普通函數(shù)的區(qū)別詳解
本文為大家講解了JavaScript中箭頭函數(shù)與普通函數(shù)的區(qū)別,供大家參考,具體內(nèi)容如下
箭頭函數(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();
箭頭函數(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)用它的那個對象
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
JavaScript 存在陷阱 刪除某一區(qū)域所有節(jié)點
實現(xiàn)功能:刪除某一區(qū)域中所有節(jié)點。2010-05-05JS中setInterval、setTimeout不能傳遞帶參數(shù)的函數(shù)的解決方案
在JS中無論是setTimeout還是setInterval,在使用函數(shù)名作為調(diào)用句柄時都不能帶參數(shù),而在許多場合必須要帶參數(shù),接下來為大家介紹具體的解決方法2013-04-04一文快速學(xué)會創(chuàng)建uni-app項目并了解pages.json文件
這篇文章主要給大家介紹了如何創(chuàng)建uni-app項目并了解pages.json文件的相關(guān)資料,pages.json文件用來對uni-app進(jìn)行全局配置,決定頁面文件的路徑、窗口樣式、原生的導(dǎo)航欄、底部的原生tabbar等,需要的朋友可以參考下2023-10-10微信小程序?qū)崿F(xiàn)手機(jī)獲取驗證碼倒計時60s
這篇文章主要為大家詳細(xì)介紹了微信小程序?qū)崿F(xiàn)手機(jī)獲取驗證碼后倒計時60s,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2022-05-05