こんにちはimデフォルトの数値ラッパー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では、「this」がNumber.toStringのtoString()の数値である必要があります。
事前にjavascriptのおかげでこれを行う方法を探しています
toString
はメソッドであり、変換するオブジェクトをthis
コンテキストとして受け取ります。それを元の関数に渡す必要があります。
Number.prototype.toString()
オプションのradix
引数を取ることができます。あなたもそれを伝えるべきです。
this
を使用して、特定のコンテキストと引数を使用して関数を呼び出すことができますFunction.prototype.apply
。
また、元の関数によって返された値を返す必要があります。
(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));
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加