繁体   English   中英

如何在覆盖后调用原始方法

[英]How to call original method after its override

In Javascript , when I override Date.prototype.toString function, the output of the Date() function is not affected and the function keeps its original code.

console.log(Date());
console.log(new Date().toString());

Date.prototype.toString = function() { return this.toISOString() }

console.log(Date());
console.log(new Date().toString());

“2021 年 1 月 26 日星期二 17:30:33 GMT-0500(东部标准时间)”

“2021 年 1 月 26 日星期二 17:30:33 GMT-0500(东部标准时间)”

“2021 年 1 月 26 日星期二 17:30:33 GMT-0500(东部标准时间)”

“2021-01-26T22:30:33.821Z”

在这里测试一下。


但是,当我需要使用更复杂的Date class 覆盖时 - 在我的情况下将时钟步长更改为 5 秒间隔 - 在我覆盖Date.prototype.toString之后,Z78E6221F6393D14CE6 的Date() 由于Date() function 的功能不应更改,因此这是不受欢迎且不受欢迎的更改。

console.log(Date());
console.log(new Date().toString());

(function() {
  let ___now = Date.now;
  Date = new Proxy(Date, {
    construct(target, args) {
      if (args[0] === undefined) args[0] = this.adjust()
      let date = new target(...args);
      return date;
    },
    apply(target, thisArg, argumentList) {
      return new Date(this.adjust()).toString();
    },
    adjust() {
      return 5000 * Math.floor(___now() / 5000);
    }
  });
})();
Date.prototype.toString = function() { return this.toISOString() }

console.log(Date());
console.log(new Date().toString());

“2021 年 1 月 26 日星期二 17:30:35 GMT-0500(东部标准时间)”

“2021 年 1 月 26 日星期二 17:30:35 GMT-0500(东部标准时间)”

“2021-01-26T22:30:35.000Z” “2021-01-26T22:30:35.000Z”

“2021-01-26T22:30:35.000Z” “2021-01-26T22:30:35.000Z”

在这里测试一下。


我应该如何修改上面的代码以强制Date() function 使用原始的toString() function,即使它被覆盖? toString()的更改应该仅在显式调用时才适用,如上面的示例所示。

以下内容应该适合您:

 console.log(Date()); console.log(new Date().toString()); (function() { const ___now = Date.now; const ___toString = Date.prototype.toString; Date = new Proxy(Date, { construct(target, args) { if (args[0] === undefined) args[0] = this.adjust() let date = new target(...args); return date; }, apply(target, thisArg, argumentList) { return ___toString.bind(new Date()).call(); }, adjust() { return 5000 * Math.floor(___now() / 5000); } }); })(); Date.prototype.toString = function() { return this.toISOString() } console.log(Date()); console.log(new Date().toString());

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM