前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >33 - 箭头函数和 new 、arguments 以及 super 关键字

33 - 箭头函数和 new 、arguments 以及 super 关键字

作者头像
前端黑板报
发布2022-12-01 17:04:27
2980
发布2022-12-01 17:04:27
举报
文章被收录于专栏:前端黑板报前端黑板报

原文地址:https://dev.to/bhagatparwinder/arrow-function-and-the-new-arguments-super-keyword-2d1l

我们之前已经学过了箭头函数以及它的 this 关键字的不同。

当涉及到 this 关键字的时候箭头函数会表现的不同,同时它也没有绑定的 argumentsnewsuper 关键字。

Arguments

arguments 对象是一个类数组使我们可以获取所有传递给函数的参数。

代码语言:javascript
复制
function addThreeNumbers(a, b, c) {
    console.log(arguments.length); // 3
    console.log(arguments[0]); // 4
    console.log(arguments[1]); // 17
    console.log(arguments[2]); // 22
    return a + b + c;
}

console.log(addThreeNumbers(4, 17, 22)); // 43

箭头函数的参数是对作用域参数的引用。

代码语言:javascript
复制
const bar = x => console.log(arguments);

console.log(bar()); // Uncaught ReferenceError: arguments is not defined

我们可以通过替代方法解决此问题,当你需要获取参数时,使用 rest 操作符。

代码语言:javascript
复制
const addThreeNumbers = (...args) => {
    console.log(args.length); // 3
    console.log(args[0]); // 4
    console.log(args[1]); // 17
    console.log(args[2]); // 22
    return args[0] + args[1] + args[2];
}

console.log(addThreeNumbers(4, 17, 22)); // 43

你可以通过解构使代码更简洁。

代码语言:javascript
复制
const addThreeNumbers = (...args) => {

    const [a, b, c] = args;

    console.log(args.length); // 3
    console.log(a); // 4
    console.log(b); // 17
    console.log(c); // 22

    return a + b + c;
}

console.log(addThreeNumbers(4, 17, 22)); // 43

New

箭头函数不能用作构造器,当和 new 一起使用时会报错。

代码语言:javascript
复制
const foo = () => { };
const bar = new foo(); // foo is not a constructor

箭头函数没有 Construct 内部方法。

Super

按照 ES 规范箭头函数不能与 super 关键字一起使用。

代码语言:javascript
复制
class Base {
    public foo = () => {
        console.log("Hello");
    }
}

class Child extends Base {
    public bar() {
        super.foo(); // Only public and protected methods of the base class are accessible via the 'super' keyword.
    };
}

然而,在这种场景下使用常规的函数。

代码语言:javascript
复制
class Base {
    public foo() {
        console.log("Hello");
    }
}

class Child extends Base {
    public bar() {
        super.foo();
    };
}

彩蛋

  • • 箭头函数没有 prototype 属性
代码语言:javascript
复制
var Foo = () => { };
   console.log(Foo.prototype); // undefined
  • • 箭头函数不能用作 generators ,因为它们没有 yield 关键字。
本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2022-08-15,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 前端黑板报 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Arguments
  • New
  • Super
  • 彩蛋
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档