简体   繁体   中英

catch missing method call with javascript proxy

How can I get this code to work. I want to intercept all missing method calls on my function, and redirect them to a "catch all" kind of method on said function.

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

var p = new Proxy(foo, {
    get: function (target, prop) {
        if (Object.keys(target).indexOf(prop) !== -1) {
          // should call existing method.
            //return target[prop]; <-- does not work.
        }else{
          // here i want to call "not_found() on foo() if prop doesnt exist
        }
    }
});

console.log(p.bar()); // should print out: found!;
console.log(p.foo()); // should print out: method not found;

thanks in advance!

foo is a function. As deepak said, if you create an object from it, it will 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()); // prints: method not found;

Since Foo is acting like a constructor, I wrote it with a capital letter. Also, the convention is to use camel case for names. Took the liberty to change these.

A slightly cleaner version (using in ):

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

var foo = new Foo();

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

console.log(p.bar()); // prints: found!;
console.log(p.foo()); // prints: method not found;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM