簡體   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