I have the following code, where I'm using Proxy object (proxy) to try to catch method calls and access of the properties:
Example: https://jsfiddle.net/r8j4fzxL/2/
(function() {
'use strict';
console.clear();
//some empty class where I want to trap methods props
class X {
//...
}
let proxy = {
get: function(target, prop, receiver) {
console.log('get called: ',
'target:', target,
'prop:', prop,
'receiver:', receiver
);
//this is OK, if we are called as a method.
//but it isn't when called as .prop - because, obviously, we return a function here.
return function(...args) {
console.log('wrapper args:', args);
return 42;
}
},
};
let p1 = new Proxy(X, proxy);
//how to distinguish the two in the above proxy:
console.log(p1.test('some arg passed'));
console.log(p1.test);
})();
And I have two questions here.
Generally, is this the right way, if I want to trap both properties access and method access? Or maybe should I go with .apply trap somehow (failed to do so though)?
If this is the right way (using .get) - then how do I know how the user accessed the... thing? Via
.foo;
or via.foo()
;?
Resources I used and apparently didn't fully understand: