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

后端 未结 2 1373
-上瘾入骨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' );
    

提交回复
热议问题