How do I trap arguments to a target method when using a Proxy object?

后端 未结 2 1372
-上瘾入骨i
-上瘾入骨i 2021-02-05 12:56

I\'m trying to use Javascript Proxy objects to trap the arguments that are passed to a \'method\' of the target that I\'m proxying.

Please consider this example:

相关标签:
2条回答
  • 2021-02-05 13:18

    There actually is a way to do this, of course! I just hadn't thought it through thoroughly enough. I can just return a 'proxy' function and trap the arguments in there:

    var test = {
        doSomething: function() {
            console.log( arguments.length );
        }
    };
    
    var testProxy = new Proxy( test, {
        get: function( target, property, receiver ) {
    
            switch( property ) {
                case 'doSomething':
                  // you just have to return a proxy function
                  return function() {
                      // arguments accessible, after all!
                      console.log( 'testProxy::doSomething() arguments.length: ' + arguments.length );
    
                      // here you can still invoke the original method, of course
                      target[ property ].apply( this, arguments );
                  }
                break
            }
    
            return target[ property ];
        }
    } );
    
    testProxy.doSomething( 'this', 'is', 'not', 'so', 'lame', 'after', 'all' );
    
    0 讨论(0)
  • 2021-02-05 13:22

    another snippet : )

    const obj_hidden = {};
    
    const obj = new Proxy(obj_hidden, {
        get(target, prop) {
            if (typeof target[prop] == 'function') {
              return function (...args) {
                console.dir({ call: [prop, ...args] });
                return target[prop].apply(target, args);
              }
            }
            console.dir({ get: prop });
            return target[prop];
        },
        set(target, prop, value) {
            console.dir({ set: [prop, value] });
            target[prop] = value;
            return true;
        }
    });
    
    0 讨论(0)
提交回复
热议问题