我正在使用 javascript 代理来拦截对对象的方法调用,但是如果该方法是不可配置且不可写的属性,我将无法正确拦截它
var handler = {
get(target, key, receiver) {
if (target[key] && (typeof target[key] === 'object' || typeof target[key] === "function")) {
var desc = Object.getOwnPropertyDescriptor(target, key);
if (desc && ! desc.configurable && !desc.writable) return Reflect.get(target,key);
var method = Reflect.get(target, key);
if (typeof method == "function") {
return function (...args) {
return method.apply(target, args);
}
} else return new Proxy(method, handler);
} else return Reflect.get(target,key);
}
}
var p = new Proxy(window, handler);
p.alert("alert message") // this works fine as I'm passing the correct context inside
// `method.apply`
p.location.valueOf(); // throws illegal invocation error as valueOf is a
//non configurable property and I can't pass my custom "function(..args){}" function
//as I do for other methods