目录
箭头函数:无名,无function声明,继承上层作用域this,非function实例
匿名函数:无名,有function声明,function实例,可变量提升
对象方法:可省function声明(对象字面量的简写),可变量提升
继承上一层作用域链的this,所以没有原型prototype,所以不能作为构造函数/创建实例
箭头函数:无名,无function声明,继承上层作用域this,非function实例
有function声明的才创造function实例
匿名函数:无名,有function声明,function实例,可变量提升
有function声明的才变量提升
对象方法:可省function声明(对象字面量的简写),可变量提升
// 箭头函数
const arrowFunction = () => {
console.log(this); // this指向定义时的外部作用域的this
};
// 传统匿名函数
const anonymousFunction = function() {
console.log(this); // this的值取决于调用方式
};
const obj = {
arrow: arrowFunction,
anonymous: anonymousFunction,
//对象字面量
literal(){
console.log(this);
}
};
obj.arrow(); // 箭头函数中的this和上文保持一致,window
obj.anonymous(); // 匿名函数中的this取决于调用方式,object
anonymousFunction();// 匿名函数中的this取决于调用方式,window
obj.literal(); // 对象字面量this为object
箭头函数:简洁
继承上一层作用域链的this,所以没有原型prototype,所以不能作为构造函数/创建实例
function声明才创建function实例
console.log(typeof (() => {}).prototype); // 输出 "function",但并非function实例对象
当函数体只有一句时,可省 return , {}
const fun = () => "S";
console.log(fun());// "S"
console.log((() => "S")());// "S"
console.log(() => "S");// () => "S"
IIFE:()()(立即调用函数表达式)/自执行函数
- 第一部分是一个具有词法作用域的匿名函数,并且用圆括号运算符
()
运算符闭合起来。这样不但阻止了外界访问 IIFE 中的变量,而且不会污染全局作用域。 - 第二部分创建了一个立即执行函数表达式
()
,通过它,JavaScript 引擎将立即执行该函数。
(function () {
// …
})();
(() => {
// …
})();
(async () => {
// …
})();
函数定义方式
A.函数声明:function变量提升
function add(x, y) {
return x + y;
}
export function(){} :工具函数Util
B.函数表达式:const暂时性死区、变量=匿名函数
const add = function(x, y) {
return x + y;
};
应用
React
this:组件实例
无论时类组件还是函数组件,都是用箭头函数表达式避免this问题,继承组件的this
同时const的暂时性死区,无变量提升,调用代码更规范
bind:constructor、标签
()=>:calss、标签
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
}
//箭头函数
//方法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>
{/* 箭头函数 */}
<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;