首页 > 解决方案 > 使 JS 类可调用而没有副作用

问题描述

对于上下文,我正在尝试重新创建本机Date对象以更好地满足我的目的,为此我使用一个类对其进行扩展,例如:

class MyDate extends Date {
  constructor(...input) {
    super(...input);
    this.change = 'example change';
    return this;
  }
}

在大多数情况下,我已经成功完成了我的任务,我的NewDate类运行良好,并且在行为上几乎与本地Date类完全匹配,但是它有一点不同:

console.log(Date()); // this works, printing your current date as a string
console.log(MyDate()); // doesn't work, gives the error below:
// Uncaught TypeError: Class constructor MyDate cannot be invoked without 'new'

那么我怎样才能复制Date同时作为类构造函数和函数的行为呢?显然有可能否则Date将无法做到这一点。

我已经尝试过:

标签: javascriptnode.jsfunctionclassprototype

解决方案


推荐阅读