如何在javascript函数对象中测试是否调用了无效方法? [重复]

时间:2021-12-17 21:33:37

This question already has an answer here:

这个问题在这里已有答案:

Given the function object:

给定函数对象:

var foo = function foo() {
    return "My methods are bar and baz";
};
foo.bar = function () {return "ok";};
foo.prototype.baz = function () {return "ok";};

If foo.bar() or foo.baz() are called, they respond with ok. However, if I try foo.wrong(), I get an error.

如果调用foo.bar()或foo.baz(),它们会响应ok。但是,如果我尝试foo.wrong(),我会收到错误。

Is there a way for the foo function object to respond with "Invalid method called"? In other words can I see what methods are being called within the foo function object to make sure they are valid (exist)?

有没有办法让foo函数对象响应“调用无效方法”?换句话说,我可以看到在foo函数对象中调用哪些方法以确保它们是有效的(存在)?

For example, since javascript searches the prototype chain for valid functions, is there a way to hook into that search and respond with a function of my own if the search fails (maybe a function I added to the prototype of foo to handle invalid methods)?

例如,由于javascript在原型链中搜索有效函数,如果搜索失败,有没有办法挂钩到该搜索并使用我自己的函数进行响应(可能是我添加到foo原型中以处理无效方法的函数) ?

I would like to test for this situation within the foo function itself and not externaly every time I attempt to call a method of the foo function object.

我想在foo函数本身内测试这种情况,而不是每次我尝试调用foo函数对象的方法时都是externaly。

Also, please stay within strict mode guidelines.

此外,请遵守严格的模式指南。

1 个解决方案

#1


3  

Since you don't want to check if a function exists every time you call it you can add a call function which checks the function name (as @Izzey suggested):

由于您不想在每次调用时检查函数是否存在,因此您可以添加一个检查函数名称的调用函数(如@Izzey建议的那样):

foo.call = function(name) {
    if('function' === typeof this[name]) {
        return this[name]();
    }else{
        console.error('function not found');
    }
}

And then call each functions by using the call(name) function:

然后使用call(name)函数调用每个函数:

foo.call('bar');

#1


3  

Since you don't want to check if a function exists every time you call it you can add a call function which checks the function name (as @Izzey suggested):

由于您不想在每次调用时检查函数是否存在,因此您可以添加一个检查函数名称的调用函数(如@Izzey建议的那样):

foo.call = function(name) {
    if('function' === typeof this[name]) {
        return this[name]();
    }else{
        console.error('function not found');
    }
}

And then call each functions by using the call(name) function:

然后使用call(name)函数调用每个函数:

foo.call('bar');