0

In the below code, How do I get access to the name of the function attempted to be called, and any params, in the catching function, in this example how can p.foo() (which is handled by the notFound function) print out the 'one','two','three' params as well. the amount of parameters should not be hardcoded as in this example 3.

I have tried replacing: return target['notFound']; with a bunch of combinations of () and [] and passing 'arguments' and even 'prop', no luck. also tried using .apply() still didnt get it to work.

var Foo = function () {
    this.bar = function () {
        return "found!";
    }
    this.notFound = function () {
        return "method not found.";
    }
};

var p = new Proxy(new Foo, {
    get: function (target, prop) {
        if (Object.keys(target).indexOf(prop) !== -1) {
            return target[prop];
        } else {
            return target['notFound'];
        }
    }
});

console.log(p.bar()); // prints: found!;
console.log(p.foo("one","two","three")); // prints: method not found;

thanks in advance!

5
  • 1
    You can just access arguments in the notFound method Commented Oct 6, 2020 at 14:03
  • well that was easy!! :) Commented Oct 6, 2020 at 14:44
  • @Bergi but what about the requested function name? its stored in 'prop' and i can echo it out in the proxy object code, but how do i get it to 'notFound' function? if i do this.notFound=function(prop){} props equals the first parameter, here "one". Commented Oct 6, 2020 at 14:59
  • 1
    In that case, instead of return target['notFound'] you'd need to return function(..args) { target.notFound(prop, ...args) }; or something like that. Or just store the accessed prop in a temporary property. Commented Oct 6, 2020 at 15:20
  • it was the wrapping it in a function that was missing. all works now, thank you! make a new answer and i can set it as accepted. Commented Oct 6, 2020 at 15:27

1 Answer 1

1

I think you're looking for

class Foo {
    bar() {
        return "found!";
    }
    notFound(name, args) {
        return `method '${name}' not found, was called with [${args.join(', ')}].`;
    }
}

var p = new Proxy(new Foo, {
    get: function (target, prop) {
        if (prop in target) {
            return target[prop];
        } else {
            return function(...args) { return target.notFound(prop, args); };
        }
    }
});

console.log(p.bar()); // prints: found!;
console.log(p.foo("one","two","three")); // prints: method 'foo' not found, was called with [one, two, three]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.