简体   繁体   English

使用 javascript 代理捕获丢失的方法调用

[英]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. foo是一个函数。 As deepak said, if you create an object from it, it will work:正如deepak所说,如果您从中创建一个对象,它将起作用:

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.因为Foo就像一个构造函数,所以我用大写字母写了它。 Also, the convention is to use camel case for names.此外,惯例是使用驼峰命名法。 Took the liberty to change these.冒昧地改变了这些。

A slightly cleaner version (using in ):稍微干净一点的版本(使用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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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