在javascript中动态调用局部函数 [英] dynamically call local function in javascript

查看:119
本文介绍了在javascript中动态调用局部函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有很多类似的问题,有关调用函数名称动态。但是,我找不到一个解决方案,我的具体问题,我有一个闭包中的局部函数,而不暴露的对象的公共接口的对象。

there are plenty of similar questions out there about calling functions by name dynamically. However, I can't find a solution to my specific problem where I have local functions inside a closure without exposing the functions to the public interface of my object.

一些代码(这是一个虚构的例子)...

Lets see some code (this is a fictional example)...

(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,并且没有暴露本地函数。
此外,我想能够在尝试调用之前检查函数是否存在。
eg。

This doesn't work because "this" is MyObject and the local functions are not exposed. Also I'd like to be able to check if the function exists before trying to call it. eg.

var func_name = 'privateMethod'+number;
if($.isFunction(this[func_name])) {
  this[func_name].apply(this,[otherarg]);
}

我不知道如何继续,到公共接口,一切都正常工作。

I'm not really sure how to proceed, short of exposing my private functions to the public interface, it all works then.

obj.privateMethod1 = function(arg) {
  //do something with arg
};

obj.privateMethod2 = function(arg) {
  //do something else with arg
};

我的想法已经不多了。非常感谢您的帮助和建议。

I'm running out of ideas. Your help and advise is greatly appreciated.

推荐答案

不能通过字符串获取对局部变量的引用。您必须将本地对象添加到命名空间:

You cannot get a reference to a local variable by a string. You have to add the local objects to a namespace:

(function(window,$) {
  // Use "var MyObject = " instead of "MyObject = "!! Otherwise, you're assigning
  //  the object to the closest parent declaration of MyVar, instead of locally!
  var MyObject = (function($) {
    var obj = {};
    var local = {};  // <-- Local namespace
    obj.publicMethod = function(number,otherarg) {
      local['privateMethod'+number].call(this, otherarg);
    };

    var privateMethod1 = local.privateMethod1 = function(arg) {
      //do something with arg
    };

    var privateMethod2 = local.privateMethod2 = function(arg) {
      //do something else with arg
    };

    return obj;
  })($);

  window.MyObject = MyObject;
})(window,jQuery);

这篇关于在javascript中动态调用局部函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆