基础04-什么时候不能使用箭头函数
箭头函数的缺点
题目
什么时候不能使用箭头函数?
箭头函数的缺点
没有 arguments
const fn1 = () => {console.log('this', arguments) // 报错,arguments is not defined
}
fn1(100, 200)
无法通过 call apply bind 等改变 this
const fn1 = () => {console.log('this', this) // window
}
fn1.call({ x: 100 })
简写的函数会变得难以阅读
const multiply = (a, b) => b === undefined ? b => a * b : a * b
不适用箭头函数的场景
对象方法
const obj = {name: '双越',getName: () => {return this.name}
}
console.log( obj.getName() )
扩展对象原型(包括构造函数的原型)
const obj = {name: '火龙'
}
obj.__proto__.getName = () => {return this.name
}
console.log( obj.getName() )
构造函数
const Foo = (name, age) => {this.name = namethis.age = age
}
const f = new Foo('火龙', 20) // 报错 Foo is not a constructor
动态上下文中的回调函数
const btn1 = document.getElementById('btn1')
btn1.addEventListener('click', () => { // console.log(this === window)this.innerHTML = 'clicked'
})
Vue 生命周期和方法
{data() { return { name: '火龙' } },methods: {getName: () => {// 报错 Cannot read properties of undefined (reading 'name')return this.name},// getName() {// return this.name // 正常// }},mounted: () => {// 报错 Cannot read properties of undefined (reading 'name')console.log('msg', this.name)},// mounted() {// console.log('msg', this.name) // 正常// }
}
【注意】class 中使用箭头函数则没问题
class Foo {constructor(name, age) {this.name = namethis.age = age}getName = () => {return this.name}
}
const f = new Foo('张三', 20)
console.log('getName', f.getName())
所以,在 React 中可以使用箭头函数
export default class HelloWorld extends React.Component {constructor(props) {super(props)this.state = {name: '双越'}}render() {return <p onClick={this.printName}>hello world</p>}printName = () => {console.log(this.state.name)}
}
答案
箭头函数的缺点
- arguments 参数
- 无法改变 this
不适用的场景
- 对象方法
- 对象原型
- 构造函数
- 动态上下文
- Vue 生命周期和方法
划重点
- Vue 组件是一个对象,而 React 组件是一个 class (如果不考虑 Composition API 和 Hooks)
你写出来的代码让所有人都能看懂那才是高级的!受教了!程序员这个职业还是脚踏实地,少出bug,少装逼!