=>箭头函数 · 方便、快捷,也要小心坑

数据库2025-11-05 06:23:2526

箭头函数是函数必须要掌握的,今天我们一起来学习一下,快捷它给开发者带来方便的心坑同时,也要留意它的函数「无能」。先看一个例子:

const names = [     wsy,快捷     suyan,     前端小课 ]; let lengths = names.map(name => name.length); console.log(lengths = , lengths); 

结果如图:

先看下它的语法:

1. 无参数

function call(callback) {     callback(); } call(() => {     console.log(arrow void); }); // 箭头函数类似于下面这个函数 call(function () {     console.log(void); }); 

2. 只有一个参数,无返回值

function call(callback) {     callback(前端小课); } call(name => {     console.log(arrow,心坑 name); }); // 箭头函数类似于下面这个函数 call(function (name) {     console.log(name); }); 

3. 只有一个参数,有返回值

function call(callback) {     // 返回值为 4     let len = callback(前端小课);     console.log(len); } // 只有一行表达式省略大括号 call(name => name.length); // 类似于这个 call(name => {     return name.length; }); // 箭头函数类似于下面这个函数 call(function (name) {     return name.length; }); 

4.有多个参数,函数有返回值

function call(callback) {     let len = callback(1,快捷 2, 3);     console.log(len); // 6 } // 多个个参数,有返回值,心坑只有一行表达式省略大括号 call((a,函数 b, c) => a + b + c); // 类似与这个 call((a, b, c) => {     return a + b + c; }); // 箭头函数类似于下面这个函数 call(function (a, b, c) {     return a + b + c; }); 

从上面这些例子可以知道,亿华云计算每个箭头函数都能写出一个与其功能相同的快捷普通函数,那为什么还用箭头函数?心坑

在 连接你、我、函数他 —— this 这节课程中使用箭头函数解决了 this 指向的快捷问题。不知道你们有没有发现当写下面这两个函数的心坑时候,VSCode 默认使用的是箭头函数:

setTimeout(() => {     // 这里是箭头函数 }, 100); setInterval(() => {     // 这个是箭头函数 }, 200); 

使用箭头函数有几点需要留意:

1. 让函数更简短,上面例 3 就是云南idc服务商一个很好的例子;

2. 没有自己的 this 和 argument,比如有如下代码:

let person = {     name: suyan,     showName: function (age) {         window.setTimeout(() => {             console.log(this = , this);             console.log(arguments = , arguments);             console.log(this.name, age);         }, 100);     } }; person.showName(20); 

打印结果为:

3. 不能作为构造函数;

let Dog = name => {     this.name = name; }; // 错误 Uncaught TypeError: Dog is not a constructor let aDog = new Dog(fe); let Dog2 = function (name) {     this.name = name; }; // 正确 let aDog2 = new Dog2(fe); 

4. 箭头函数没有 prototype 属性:

let Dog = name => {     this.name = name; }; Dog.prototype; // undefined 

5.不能通过 call、apply 绑定 this

var name = I am widow; let animal = {     name: animal,     showName: age => {         console.log(this = , this);         console.log(name | age = , this.name, age);     } }; let dog = {     name: dog }; animal.showName.call(dog, 20); animal.showName.apply(dog, [21]); let bindName = animal.showName.bind(dog, 22); bindName(); 

运行代码,结果如下:

由于箭头函数没有 this 指针,不能通过 call、apply、bind 的方式来修改 this。只能传递参数,this 参数将被忽略。

本文地址:http://www.bzuk.cn/news/359d34799293.html
版权声明

本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。

全站热门

台式电脑内置喇叭安装教程(一步步教你如何给台式电脑安装内置喇叭)

能用 AST 搞明白的正则语法,就不需要看文档

如何在 Spring Boot 优雅关闭加入一些自定义机制

600多种计算机语言,到底学习哪种可以发家致富呀?

以建荣SD卡量产工具教程(关键步骤详解,让你快速掌握SD卡量产技巧)

MySQL 5.7版本新特性(三)

解DBA之惑:数据库承载能力评估及其优化手段

腾讯互娱是这样利用游戏大数据的

友情链接

滇ICP备2023006006号-33