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

查看:15
本文介绍了在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 并且未公开本地函数.另外,我希望能够在尝试调用该函数之前检查该函数是否存在.例如.

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天全站免登陆