覆盖 javascript 中的 toString 函数

override toString function in javascript

嗨,我正在尝试覆盖默认的 Number 包装器 toString 函数

(function() {
  let _toString = Number.prototype.toString;
  Number.prototype.toString = function() {
    console.log("Number ToString Called");
    _toString();
  };
})();

let b = new Number(5);
console.log(b);
document.writeln(typeof b);
document.writeln(b.toString());

我使用了上面的代码,但是当我尝试在 console.log()

之后调用原始方法时它给了我错误

Uncaught TypeError: Number.prototype.toString requires that 'this' be a Number at toString () at Number.toString

我正在寻找在 javascript 中执行此操作的方法 提前致谢

(function() {
  let _toString = Number.prototype.toString;
  Number.prototype.toString = function() {
    console.log("Number ToString Called");
    return _toString.call(this);// Set the this on which to apply toString & return it
  };
})();

let b = new Number(5);
console.log(b);
document.writeln(typeof b);
document.writeln(b.toString());

toString 是一种方法,它接收要转换的对象作为其 this 上下文。您需要将其传递给原始函数。

Number.prototype.toString() 可以采用可选的 radix 参数。你也应该传递它。

您可以使用 Function.prototype.apply.

调用具有特定 this 上下文和参数的函数

您还需要 return 由原始函数 return 编辑的值。

(function() {
  let _toString = Number.prototype.toString;
  Number.prototype.toString = function(...args) {
    console.log("Number ToString Called");
    return _toString.apply(this, args);
  };
})();

let b = new Number(20);
console.log(b);
document.writeln(typeof b);
document.writeln(b.toString());
document.writeln(b.toString(8));