目錄
匿名/箭頭函數(shù):簡潔
繼承上一層作用域鏈的this
不綁定arguments,用rest參數(shù)
?rest 參數(shù):...真正的數(shù)組
因為沒有function聲明,所以沒有原型prototype,所以不能作為構(gòu)造函數(shù)
當函數(shù)體只有一句時,可省 return ,?{}
IIFE:()()(立即調(diào)用函數(shù)表達式)/自執(zhí)行匿名函數(shù)
函數(shù)定義方式
A.函數(shù)聲明:function變量提升
B.函數(shù)表達式:const暫時性死區(qū)
應(yīng)用:React
this:組件實例
bind:constructor、標簽
()=>:calss、標簽
匿名/箭頭函數(shù):簡潔
繼承上一層作用域鏈的this
不綁定arguments,用rest參數(shù)
?rest 參數(shù):...真正的數(shù)組
function sum(...numbers) {
let total = 0;
for (let number of numbers) {
total += number;
}
return total;
}
console.log(sum(1, 2, 3)); // 輸出 6
因為沒有function聲明,所以沒有原型prototype,所以不能作為構(gòu)造函數(shù)
當函數(shù)體只有一句時,可省 return ,?{}
const fun = () => "S";
console.log(fun());// "S"
console.log((() => "S")());// "S"
console.log(() => "S");// () => "S"
IIFE:()()(立即調(diào)用函數(shù)表達式)/自執(zhí)行匿名函數(shù)
- 第一部分是一個具有詞法作用域的匿名函數(shù),并且用圓括號運算符?
()
?運算符閉合起來。這樣不但阻止了外界訪問 IIFE 中的變量,而且不會污染全局作用域。 - 第二部分創(chuàng)建了一個立即執(zhí)行函數(shù)表達式?
()
,通過它,JavaScript 引擎將立即執(zhí)行該函數(shù)。
(function () {
// …
})();
(() => {
// …
})();
(async () => {
// …
})();
函數(shù)定義方式
A.函數(shù)聲明:function變量提升
類內(nèi)function不用function聲明,但也可變量提升
? ?function add(x, y) {
? ? ?return x + y;
? ?}
B.函數(shù)表達式:const暫時性死區(qū)
const、let、calss不會提升
? ?const add = function(x, y) {
? ? ?return x + y;
? ?};
應(yīng)用:React
this:組件實例
無論時類組件還是函數(shù)組件,都是用箭頭函數(shù)表達式避免this問題文章來源:http://www.zghlxwxcb.cn/news/detail-805871.html
bind:constructor、標簽
()=>:calss、標簽
文章來源地址http://www.zghlxwxcb.cn/news/detail-805871.html
import React, { Component } from 'react'; // 請確保導入 React 和 Component
class APP extends Component {
constructor(props) {
super(props);
// 將 handleClick 方法綁定到組件實例的上下文
this.handleClick5 = this.handleClick5.bind(this);
}
handleClick1(ev) {
console.log(this);//undefined
console.log(ev);//合成的SyntheticBaseEvent?
console.log(ev.target);//button
}
//箭頭函數(shù)
//方法A:類中箭頭
handleClick2 = () => {
console.log(this);//APP類組件實例
}
//方法B:onclick中箭頭
handleClick3() {
console.log(this);//APP類組件實例
}
// bind綁定組件實例this
// 方法A:onclick
handleClick4() {
console.log(this); //APP類組件實例
}
// 方法B:constructor
handleClick5() {
console.log(this); //APP類組件實例
}
render() {
return (
<div>
<button onClick={this.handleClick1}>點擊1</button>
{/* 箭頭函數(shù) */}
<button onClick={this.handleClick2}>點擊2</button>
<button onClick={() => { this.handleClick3() }}>點擊3</button>
{/* bind */}
<button onClick={this.handleClick4.bind(this)}>點擊4</button>
<button onClick={this.handleClick5}>點擊5</button>
</div>
);
}
}
export default APP;
到了這里,關(guān)于匿名/箭頭函數(shù),立即執(zhí)行函數(shù)IIFE;函數(shù)聲明式和函數(shù)表達式的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!