我在尝试覆盖 Function
原型(prototype)时遇到了一个有趣的行为。
假设我们已经像这样覆盖了 toString():
const funcToString = Function.prototype.toString;
Function.prototype.toString = function() {
console.log("lol");
return funcToString.call(this);
}
现在,让我们付诸行动,看看会发生什么:
(function foo(){}).toString(); // TypeError
TypeError: Function.prototype.toString requires that 'this' be a Function
通过阅读,我了解到这与 Function 内部如何将其包装在 Proxy 中有关 - 它与目标无法区分,导致 TypeError。
但是现在,我们可以尝试这样做:
function boo(){};
boo.toString(); // prints "lol", as we wanted
除此之外,我只在浏览器运行时观察到了这种行为。在 Node.js 中,这两种情况下一切都很顺利。
编辑:确认可以在 REPL 中正常工作,没有任何错误。
就我个人而言,我不明白区别是什么/到底发生了什么。 如果有人能对此有所了解,将不胜感激。
最佳答案
这是缺少分号的问题:
Function.prototype.toString = function() {
…
}; /*
^ */
(function foo(){}).toString();
否则解释为
Function.prototype.toString = function(){…}(function foo(){}).toString();
调用应该像 IIFE 一样覆盖 toString
的函数表达式
… (function(){…}(function foo(){})) …
...在全局上下文中,而不是在函数上。
关于javascript - 覆盖函数类型原型(prototype),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48659417/