[英]catch missing method call with javascript proxy
我怎样才能让这个代码工作。 我想拦截我的函数上所有丢失的方法调用,并将它们重定向到所述函数上的“捕获所有”类型的方法。
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;
提前致谢!
foo
是一个函数。 正如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;
因为Foo
就像一个构造函数,所以我用大写字母写了它。 此外,惯例是使用驼峰命名法。 冒昧地改变了这些。
稍微干净一点的版本(使用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.