How Do I Trap Arguments To A Target Method When Using A Proxy Object?
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: var test = { doSom
Solution 1:
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 = newProxy( test, {
get: function( target, property, receiver ) {
switch( property ) {
case'doSomething':
// you just have to return a proxy functionreturnfunction() {
// 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' );
Solution 2:
another snippet : )
const obj_hidden = {};
const obj = newProxy(obj_hidden, {
get(target, prop) {
if (typeof target[prop] == 'function') {
returnfunction (...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;
returntrue;
}
});
Solution 3:
Thanks for sharing your answer. It helped me figure out how to fix my problem, which is fairly similar to this one. I figured I share mine as well, maybe it will be helpful.
I intended to wrap the arguments of the callback function passed to promise objects(the resolve and reject function when creating a new promise). So I created a proxy for Promise object to modify the constructor, but in the constructor, I couldn't access the arguments of the first argument of the promise constructor. This is how I did it, thanks to Decent's answer
// Wrap promise:let promiseWrapperHandlers = {
construct: function(target, args) {
let originalCb = args[0]
if (typeof args[0] === 'function') {
let wrappedCb = function() {
let resFn = arguments[0] || (() => {})
let wrappedResolve = function(v) {
console.log("resolving promise with " + v);
returnresFn(v);
}
let rejFn = arguments[1] || (() => {})
let wrappedReject = function(err) {
console.log("rejecting promise with " + err);
returnrejFn(err);
}
returnoriginalCb(wrappedResolve, wrappedReject)
}
args[0] = wrappedCb
}
let p = newtarget(...args)
return p
},
}
constRealPromise = PromisePromise = newProxy(RealPromise, promiseWrapperHandlers)
// END wrap promiseconst p = newPromise((resolve, reject) => {
resolve(122)
})
const p2 = newPromise((resolve, reject) => {
reject(121)
})
Post a Comment for "How Do I Trap Arguments To A Target Method When Using A Proxy Object?"