有没有办法捕获尝试访问不存在的属性或方法? [英] Is there a way to catch an attempt to access a non existant property or method?
问题描述
例如这段代码:
function stuff() {
this.onlyMethod = function () {
return something;
}
}
// some error is thrown
stuff().nonExistant();
有没有办法做一些像PHP的 __ call
作为对象内部的后退?
Is there a way to do something like PHP's __call
as a fallback from inside the object?
function stuff() {
this.onlyMethod = function () {
return something;
}
// "catcher" function
this.__call__ = function (name, params) {
alert(name + " can't be called.");
}
}
// would then raise the alert "nonExistant can't be called".
stuff().nonExistant();
也许我会解释一下我正在做的事情。
该对象包含另一个对象,该对象具有应该可以通过此对象直接访问的方法。但是这些方法对于每个对象都是不同的,所以我不能只是路由它们,我需要能够动态地调用它们。
The object contains another object, which has methods that should be accessible directly through this object. But those methods are different for each object, so I can't just route them, i need to be able to call them dynamically.
我知道我可以做到其中的对象是主对象的属性 stuff.obj.existant()
,但我只是想知道我是否可以避免它,因为主要对象是一种类型的只是暂时添加一些功能的包装器(并且可以更容易地同时访问对象)。
I know I could just make the object inside it a property of the main object stuff.obj.existant()
, but I'm just wondering if I could avoid it, since the main object is sort of a wrapper that just adds some functionality temporarily (and makes it easier to access the object at the same time).
推荐答案
有一个为不存在的方法调用定义通用处理程序的方法,但它是非标准的。查看Firefox的 noSuchMethod 。将允许您动态地将调用路由到未定义的方法。似乎v8也是获得支持。
There is a way to define a generic handler for calls on non-existant methods, but it is non-standard. Checkout the noSuchMethod for Firefox. Will let you route calls to undefined methods dynamically. Seems like v8 is also getting support for it.
要使用它,请在任何对象上定义此方法:
To use it, define this method on any object:
var a = {};
a.__noSuchMethod__ = function(name, args) {
console.log("method %s does not exist", name);
};
a.doSomething(); // logs "method doSomething does not exist"
但是,如果你想要一个跨浏览器的方法,然后简单的try-catch阻止如果要走的路:
However, if you want a cross-browser method, then simple try-catch blocks if the way to go:
try {
a.doSomething();
}
catch(e) {
// do something
}
如果你不想在整个代码中编写try-catch,那么你可以在主对象中添加一个包装器,通过它来路由所有函数调用。
If you don't want to write try-catch throughout the code, then you could add a wrapper to the main object through which all function calls are routed.
function main() {
this.call = function(name, args) {
if(this[name] && typeof this[name] == 'function') {
this[name].call(args);
}
else {
// handle non-existant method
}
},
this.a = function() {
alert("a");
}
}
var object = new main();
object.call('a') // alerts "a"
object.call('garbage') // goes into error-handling code
这篇关于有没有办法捕获尝试访问不存在的属性或方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!