提问者:小点点

在使用代理对象时,如何将参数捕获到目标方法?


我尝试使用Javascriptproxy对象来捕获传递给我代理的目标的“方法”的参数。

请考虑这个例子:

var test = {
    doSomething: function() {
        console.log( arguments.length );
    }
};

var testProxy = new Proxy( test, {
    get: function( target, property, receiver ) {

        // I'd like to have access to any arguments when
        // the property being accessed here is a function
        // that is being called

        return target[ property ];
    }
} );

testProxy.doSomething( 'this', 'is', 'lame' ); // I want to trap those arguments

当属性实际上是一个函数时,这些proxy对象似乎只允许您捕获对属性的访问,而不允许您捕获对实际函数调用及其参数的访问。

在对这个问题进行了一些思考之后,我“了解”到(请原谅这个双关语)get方法只是用于属性访问,而不是调用,但是我还希望能够在proxy中定义类似于call方法的内容。

proxy中定义一个apply方法可能是可行的,但是我可能必须为要代理的对象的每个单独方法创建一个proxy对象;这不是我想要的。

除非我在这里忽略了一个实际的替代可能性:proxy实现中为什么忽略了这一点?!代理的全部意义不就是能够截获方法调用及其参数吗?

或者这是我对Javascript的另一个误解,我认为Javascript不是一种“经典的”OOP语言,我所寻找的功能在Javascript上下文中实际上没有意义?


共1个答案

匿名用户

当然,实际上是有办法做到这一点的!我只是考虑得不够周全。我可以返回一个'proxy'函数,并在其中捕获参数:

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' );