【发布时间】:2021-05-05 17:40:29
【问题描述】:
在类的方法内部使用时,逻辑不起作用,但如果我在函数式样式中使用它,则在外部起作用。
class Hook {
constructor(object) {
this.object = object;
}
toStringProperty() {
const handler = {
apply: function (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();
// Interesting enough this when called (I use Devtools) logs Proxy Object itself but only happen if I use a Class
console.log(Function.prototype.toString)
console.log(HTMLAudioElement.toString())
我应该怎么做才能使它在一个类中工作?
【问题讨论】:
-
你想完成什么?
-
我认为你需要在创建类之后创建代理。
-
@PatrickRoberts 什么都没有。只是用一个类来试验 ES6 Proxy。
-
@luekbaja 看代码可以看到我在类初始化后创建了代理,
-
我不明白这个问题。 什么不起作用?
标签: javascript es6-proxy