javascript - 使 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
将无法做到这一点。
我已经尝试过:
- 弄乱原型(
.prototype
和.__proto__
)虽然有很多方法可以篡改那些我不会感到惊讶我错过了一些非常模糊的警告。 - 调用一个函数
MyDate
,它返回字符串或我的类构造函数,它实际上可以工作但会中断new MyDate instanceof Date
(因为它变成了 Function 的实例) - 这个问题的每个最佳答案:如何使用 ES6 类扩展函数?| 他们都以某种方式工作,但又闯入了另一种方式。
解决方案
推荐阅读
- python - 允许使用 Windows 登录的散景服务器上的一组用户
- ios - 如何将 If/Else 切换到 For 循环?
- java - 如果 B 依赖于 C 但 C 是在 A 中创建的,如何将依赖 B 传递给 A?
- model-view-controller - 预览页面生成器在 Kentico 12 MVC 中不起作用
- javascript - 如何编写更新函数,以便我的编辑表单更新现有文本并将其替换为其他内容?
- reveal.js - reveal.js:是否有从数据文件开始在演示文稿中插入字符串的本地方法?
- angular - 升级到 Angular 11 后获取“必须从注入上下文调用注入()”
- python - Kivy Recycleview 不会更新添加的数据
- python - 如何仅获取 member.roles Discord.py 的名称
- php - 计算最大值 where substring = substring-?