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

92 阅读3分钟

携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第3,点击查看活动详情

原文地址:dev.to/bhagatparwi…

在 JavaScript 中,你若想在一个确定的时候后执行某段代码,就需要一个定时器。在固定的时间段后,你如果想重复执行代码则需要间隔定时器。

Timer

Timers 是使用 setTimeout 来实现的:

setTimeout(() => {
    console.log("hello");
}, 2000);

第一个参数永远是一个函数或一段可执行的代码。在这个例子中,我们在控制台输出 "hello",第二个参数是定时器持续的毫秒,例子中 2s 后会在控制台打印 "hello"。

我们可以在第二个参数后面传递多个参数,这些参数会被传递到执行的函数里面。

Intervals

Intervals 是使用 setInterval 来实现的。

setInterval(() => {
    console.log("hello");
}, 2000);

setIntervalsetTimeout 的语法一样,在 setInterval 中,控制台将会每隔 2s 打印出 "hello",代码会一直打印字符串直到我们清除间隔定时器。

停止/清空定时器

setTimeoutsetInterval 都会返回一个唯一的 ID,如果我们把 ID 保存到一个变量,我们可以通过它清空/停止定时器。

清空定时器使用 clearTimeout,清空间隔定时器使用 clearInterval

const intervalId = setInterval(() => {
    console.log("hello");
}, 2000);

clearInterval(intervalId);

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

原文地址:dev.to/bhagatparwi…

我们之前已经学过了箭头函数以及它的 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

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

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 {
    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.
    };
}

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

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

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

彩蛋

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