全部 / 前端 / 技术 · 2022年6月12日 0

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

广告位招租 (vx: ghostcode, 备注:网站广告)

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

我们前面已经学了有关箭头函数以及它与其他函数的不同,还有关键字 this 的内容。

当涉及到 this 关键字的时候箭头函数表现的有点不同,它内部没有绑定 argumentsnewsuper 关键字!

Arguments

arguments 对象是一个类数组对象,可以帮助我们获取传入函数的参数。

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

箭头函数的 arguments 是对包围范围内的参数的引用。

const bar = x => console.log(arguments);

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

我们可以通过一个变通的方法来解决此问题,就是使用 rest 操作符来获取传入函数的参数。

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

你还可以通过解构来使例子更简洁:

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 与箭头函数一起使用的时候会报错:

const foo = () => { };
const bar = new foo(); // foo is not a constructor

是因为箭头函数缺失了一个内部方法 Construct

Super

根据 ES 规范我们依旧不能在箭头函数中使用 super 关键字。

class Base {
    foo = () => {
        console.log("Hello");
    }
}

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

在这个例子中我们可以用常规方法,例如:

class Base {
    foo() {
        console.log("Hello");
    }
}

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

其他

  • 箭头函数没有 prototype 属性
   var Foo = () => { };
   console.log(Foo.prototype); // undefined
  • 箭头函数也不能用作 generators ,他们没有 yield 关键字。

前端黑板报