javascript - 为什么这个代理处理程序会导致无限递归?
问题描述
toString
我使用 ES6 Proxy为该方法构建了一个钩子。在调试一些问题时,我注意到console.log
处理程序无缘无故地被调用。
class Hook {
constructor(object) {
this.object = object;
}
toStringProperty() {
const handler = {
apply: (target, thisArg, args) => {
console.log(target, thisArg, args);
if (thisArg === Function.prototype.toString) {
return 'function toString() { [native code] }'
}
if (thisArg === this.object) {
return "Hooked String"
}
return target.apply(thisArg, args)
}
}
Function.prototype.toString = new Proxy(Function.prototype.toString, handler)
}
}
let hook = new Hook(HTMLAudioElement);
hook.toStringProperty()
HTMLAudioElement.toString();
我花了很多时间试图找出导致这种递归的原因,但我担心我找不到任何东西。
HTMLAudioElement
注意:在输入或在控制台中也会发生此行为ooo
,当然您必须在运行上述代码后执行此操作。我的浏览器是 Chrome。我使用 Devtools 控制台进行了测试。
解决方案
在处理程序内部,您调用console.log(target, thisArg, args);
wheretarget
和thisArg
are 函数。devtools 控制台似乎用于.toString()
获取要显示它的函数的名称。
推荐阅读
- c# - C# - Windows 窗体 - SQLite
- javascript - 复制文本到带有按钮和 JS 的剪贴板?
- django - 获取自定义Manager中没有重复记录的OneToMany关系的“一”端
- python-3.x - Pandas 重置多级索引顺序
- python - Python“未定义变量'口味”pylint
- node.js - 如何在 Firebase Firestore 中使用 arrayUnion() 将对象推送到数组中?
- javascript - PHP数据库搜索结果查询可点击url
- css - 自定义 CSS 与 Kendo UI Grid 相混淆
- java - NotificationCompat.Builder 已弃用怎么办?
- c++ - 如何将值直接加载到 myCircleArry