关于按名称动态调用函数,有很多类似的问题。但是,我找不到针对我的特定问题的解决方案,因为我在闭包中有本地函数,但没有将这些函数公开到我的对象的公共(public)接口(interface)。
让我们看一些代码(这是一个虚构的例子)...
(function(window,$) {
MyObject = (function($) {
var obj = {};
obj.publicMethod = function(number,otherarg) {
this['privateMethod'+number].apply(this,[otherarg]);
};
var privateMethod1 = function(arg) {
//do something with arg
};
var privateMethod2 = function(arg) {
//do something else with arg
};
return obj;
})($);
window.MyObject = MyObject;
})(window,jQuery);
这不起作用,因为“this”是 MyObject 并且本地函数未公开。 此外,我希望能够在尝试调用函数之前检查该函数是否存在。 例如。
var func_name = 'privateMethod'+number;
if($.isFunction(this[func_name])) {
this[func_name].apply(this,[otherarg]);
}
我不太确定如何继续,除非将我的私有(private)函数暴露给公共(public)接口(interface),否则一切正常。
obj.privateMethod1 = function(arg) {
//do something with arg
};
obj.privateMethod2 = function(arg) {
//do something else with arg
};
我的想法已经用完了。非常感谢您的帮助和建议。
最佳答案
私有(private)函数是局部变量,不属于任何对象。因此,用于访问属性的 [...]
表示法永远不会起作用,因为不存在私有(private)函数是其属性的对象。
相反,您可以创建两个对象:private
和 public
:
var public = {},
private = {};
public.publicMethod = function(number, otherarg) {
// `.apply` with a fixed array can be replaced with `.call`
private['privateMethod' + number].call(this, otherarg);
};
private.privateMethod1 = function(arg) {
//do something with arg
};
private.privateMethod2 = function(arg) {
//do something else with arg
};
return public; // expose public, but not private
关于javascript - 在javascript中动态调用本地函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9464921/