简体   繁体   English

当我将其名称作为字符串时,如何执行私有JavaScript函数

[英]How to execute a private JavaScript function when I have its name as a string

I'm trying to execute an private function from within the returned object. 我正在尝试从返回的对象中执行私有函数。 If I knew the name of the function ahead of time this is easy but in this case I won't know what functions are available. 如果我提前知道函数的名称,这很容易,但在这种情况下,我不知道有哪些函数可用。 What I have is the a string with the name of the function to call. 我所拥有的是一个字符串,其中包含要调用的函数的名称。 Is there a way to call these functions via a string? 有没有办法通过字符串调用这些函数?

function foo() {

  // some misc. chunk of valid javascipt code
  function bar() {
      console.log("hello");
  }
  // end misc. code

  // I would like to avoid doing this if I don't have to
  var executableFn = {};
  executableFn.test = function() {
    bar();
  }
  // end

  return {
    // This works but requires I know the name of the funciton ahead of time.
    // All I have is a string name of the function to call.
    funcRunner0: function() {
      bar();
    }, 
    // My ideal method for calling but does not work
    funcRunner1: function(functionName) {
      foo[functionName]();
    }, 
    // This works but I'm trying to avoid eval.  I'm not sure if this is not so bad
    funcRunner2: function(functionName) {
      var func = eval(functionName);
      func();
    },
    // This works.  I'm not sure if this is worse than funcRunner2 or the same;
    funcRunner3: function(functionName) {
      eval(functionName + "()");
    },
    // This works but requires the executableFn object which I would like to avoid if at all possible.
    funcRunner4: function(functionName) {
      executableFn[functionName]();
    }, 
  };
}

var bas = foo();

// This works but assumes I know the name of the function to call which I don't. 
bas.funcRunner0();
// This doesn't work
bas.funcRunner1("bar");
// This works
bas.funcRunner2("bar");
// This works
bas.funcRunner3("bar");
// This works but is not my ideal
bas.funcRunner4("test");

These are all the ways I have come up with to call this function. 这些是我用来调用此功能的所有方法。 What do you think is the best way for me to call the bar function with a string? 您认为用字符串调用bar函数的最佳方法是什么? Thanks for you help. 谢谢你的帮助。

My ideal method for calling but does not work 我理想的呼叫方法但不起作用

 foo[functionName](); 

Yes, that's trying to access a [public] property on the foo function. 是的,那是试图访问foo函数的[public]属性。 It would work with the "call" method, for example. 例如,它可以使用"call"方法。

This works but I'm trying to avoid eval. 这有效,但我试图避免评估。 I'm not sure if this is not so bad 我不确定这不是那么糟糕

 var func = eval(functionName); func(); 

This works. 这有效。 I'm not sure if this is worse than funcRunner2 or the same; 我不确定这是否比funcRunner2更差或相同;

 eval(functionName + "()"); 

Both are as bad as the other from eval s perspective. eval的角度来看,两者都和另一个一样糟糕。 Option 1 just does make it easier to work with arguments [which need not be dynamically evaluated]. 选项1确实使得更容易使用参数[不需要动态评估]。

This works but requires the exec object which I would like to avoid if at all possible. 这可以工作,但需要exec对象,如果可能的话我想避免。

 exec[functionName](); 

That's just the way to do it. 这只是做到这一点的方式。 Since exec is a local variable in the foo scope, you even have your privateness. 由于execfoo范围内的局部变量,因此您甚至可以拥有自己的私有性。 It seems you have switched exec for publicObj as well 看来你也已经为publicObj切换了exec

 // I would like to avoid doing this if I don't have to var publicObj = {}; publicObj.test = function() { bar(); } 

The publicObj variable is, despite its name, not public - it's declared local with the var keyword! publicObj变量尽管名称不公开,但它是用var关键字声明的本地变量! Btw, you could've simplified this to 顺便说一下,你可以把它简化为

var exec = {
    test: bar
};

Why not make a private namespace (object) and use that instead of exec/eval? 为什么不创建一个私有命名空间(对象)并使用它而不是exec / eval?

function foo() {

    var private_ns = {
        bar : function() {
            console.log('bar', arguments);
        }
    };

    return {
        call_func: function(name) {
            if(name in private_ns) {
                var args = [].slice.call(arguments, 1)
                return private_ns[name].apply(null, args);
            } else {
                console.error('no such function');
            }
        }
    };
}

var f = foo();

> f.call_func('bar', 1, 2, 3);
bar { '0': 1, '1': 2, '2': 3 }

> f.call_func('noop');
no such function

It's somewhat similar to your "not ideal" solution, but is a bit difference. 它有点类似于你的“不理想”解决方案,但有点不同。 If you organize all of your functions into an object, you can then call them. 如果将所有函数组织到对象中,则可以调用它们。 No need for another function within an object that calls the original function. 在调用原始函数的对象中不需要其他函数。

http://jsfiddle.net/L3n4Z/ http://jsfiddle.net/L3n4Z/

function foo() {

    // all functions stored in this object
    var functions = {
        bar : function() {
          console.log("hello");
        }
    };

  return {
    funcRunner: function(funcName) {
      functions[funcName]();
    }
  };
}

var bas = foo();
bas.funcRunner("bar");

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 当我将其名称作为字符串时如何执行 JavaScript function - How to execute a JavaScript function when I have its name as a string 当我将其名称作为字符串时执行 JavaScript 函数 - 不工作 - Execute a JavaScript function when I have its name as a string - Not working 如何执行 JavaScript Function 当我将其名称作为字符串时(使用具有重载参数的参数) - How to execute a JavaScript Function When I have its name as a string (with parameters that have an overload argument) 当其名称作为字符串传递给函数时,如何执行JavaScript函数? - How to execute a JavaScript function when its name is passed as a string in function? 当我不带参数动态将其名称作为字符串发送时,如何执行javascript函数 - how to execute javascript function when i send its name as string dynamically with out parameters 如何在Edge中执行名称为字符串的JavaScript函数 - How to execute a JavaScript function having its name as a string in Edge 当我将其名称作为字符串时如何执行Angular控制器方法 - How to execute a Angular controller method when I have its name as a string 通过名称(字符串)在类内部执行私有函数 - Execute private function inside the class by its name (string) 当我有 function 名称时执行 function 的正确方法 - Correct way to execute a function when I have function name 如何从HTML元素执行javascript函数并发送该元素名称,而无需专门使用其名称? - How do I execute a javascript function from an HTML element and send that elements name without use its name specifically?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM