js es6 proxy 对象调用问题?

wuchuguang
  • 35
var twice = {
  apply (target, ctx, args) {
    console.log("apply:" + target);
    return Reflect.apply(...arguments) * 2;
  }
};
var sum = {
    ss(){
        console.log("sum ss()");
        return 200;
    }
};
var proxy = new Proxy(sum, twice);
//这里为什么不会打印出 console.log("apply:" + target);
//只打印            console.log("sum ss()");
proxy.ss();
回复
阅读 2.6k
2 个回答
✓ 已被采纳

sum又不是函数,怎么能在twice里用apply? 应该用get

var twice = {
  get (target, ctx, args) {
    console.log("apply:" + target);
    return function(){
        return target[ctx]() * 2;
    };
  }
};
var sum = {
    ss(){
        console.log("sum ss()");
        return 200;
    }
};
var proxy = new Proxy(sum, twice);
//这里为什么不会打印出 console.log("apply:" + target);
//只打印            console.log("sum ss()");
console.log(proxy.ss());

apply 只能拦截对 proxy 本身的调用,不能拦截对 proxy 下面的方法的调用:

This trap can intercept these operations:

  • proxy(...args)

  • Function.prototype.apply() and Function.prototype.call()

  • Reflect.apply()

via https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy/handler/apply

你仔细想想 JavaScript 这种「函数为一等公民」的设计,就会发现这样是有道理的。

不过,你可以这么 workaround:

var twice = {
    get (target, property, receiver) {
        return () => (Reflect.apply(target[property], target, arguments) * 2);
    }
};

var sum = {
    ss () {
        console.log("sum ss()");
        return 200;
    }
};

var proxy = new Proxy(sum, twice);
proxy.ss();
你知道吗?

宣传栏