ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

什么时候不能使用箭头函数?

2022-05-11 23:36:19  阅读:153  来源: 互联网

标签:const 函数 getName js 箭头 log 使用 console name


  ## 箭头函数的缺点
没有 arguments
```js const fn1 = () => {     console.log('this', arguments) // 报错,arguments is not defined } fn1(100, 200) ```
无法通过 call apply bind 等改变 this
```js const fn1 = () => {     console.log('this', this) // window } fn1.call({ x: 100 }) ```
简写的函数会变得难以阅读
```js const multiply = (a, b) => b === undefined ? b => a * b : a * b ```
## 不适用箭头函数的场景
对象方法
```js const obj = {     name: 'xx',     getName: () => {         return this.name     } } console.log( obj.getName() ) ```
扩展对象原型(包括构造函数的原型)
```js const obj = {     name: 'xx' } obj.__proto__.getName = () => {     return this.name } console.log( obj.getName() ) ```
构造函数
```js const Foo = (name, age) => {     this.name = name     this.age = age } const f = new Foo('张三', 20) // 报错 Foo is not a constructor ```
动态上下文中的回调函数
```js const btn1 = document.getElementById('btn1') btn1.addEventListener('click', () => {       // console.log(this === window)     this.innerHTML = 'clicked' }) ```
Vue 生命周期和方法
```js {     data() { return { name: 'xx' } },     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 中使用箭头函数则**没问题**
```js class Foo {     constructor(name, age) {         this.name = name         this.age = age     }     getName = () => {         return this.name     } } const f = new Foo('张三', 20) console.log('getName', f.getName()) ```
所以,在 React 中可以使用箭头函数
```js 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)

标签:const,函数,getName,js,箭头,log,使用,console,name
来源: https://www.cnblogs.com/lxl0419/p/16260432.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有