开发者

Javascript function name as a string in self executing function

I am running a self executing f开发者_运维问答unction in javascript to not interfere with any global variables on a page. I have a string with the name of a function I want to call. The function is declared inside my self-executing function. Is there a way to call that function by using the string?

(function(document, window){
    var functionName = "myFunction";

    window[functionName](); //This does not work...        

    function myFunction(){
        //Do some stuff
    }

}(document, window)

I found this: How to execute a JavaScript function when I have its name as a string

but my function is self executing without a name, so I have no way to reference it with the window variable.


This is just a cleaner version of what others have suggested, no global pollution, no eval, and no obscure variable references (arguments.callee and "this").

// Not sure why you were passing in doc and window, so I took it out for clarity
(function(){
    var funcs = {
      funcA: function () { return "a"},
      funcB: function () { return "b"}
    };

    var functionName = "funcA";
    funcs[functionName]();  
}();

This approach does require you to declare the functions before you use them.


Without global pollution and avoids the non-strict arguments.callee method.

Based on this answer.

// This Immediately Invoked Function Expression is invoked via `call`.
// call() takes 1 or more arguments: the first being the scope you want the 
// invoked function be in; the other arguments become arguments of the function
// itself.
// In this case, the scope of our function is an empty object ({}).
// This object allows us to attach functions using the this.* syntax and call the 
// functions with this["string"]() without ever polluting the global namespace. 
// It is also forward compatible with ECMAScript 5's scrict-mode as it does not
// use arguments.callee.
(function(document, window){
    var functionName = "myFunction";

    // you'll need to define the function _before_ you call it.
    this.myFunction = function(){
        //Do some stuff
        alert('me');
    };


    this[functionName]();

}.call({}, document, window));


If you don't mind defining the function before you call it, you can use arguments.callee. This avoids eval.

(function (){
  arguments.callee.f = function() {
    console.log('test');
  };
  arguments.callee['f']();
})();


Can you just store the myFunction function somewhere (such as on this a new object)?

See jsFiddle example:

(function (document, window){
    var functionName = "myFunction",
        myFunctions = {
            myFunction: function() { alert('myFunction'); }
        };

    myFunctions[functionName]();
}(document, window));


You can use eval(functionName + "()") since any function of window is also a global function.


I guess I can't comment on answers, so I have to post it this way. Eval is too dangerous for me, since the actual function name is given by the user in a string.


You are correct. This is because your function is defined inside your self-executing function. Window has no knowledge of the inner closure. The best you could do is probably eval:

a la:

eval(functionName + "();");

, and it's probably not all that evil in this case: When is JavaScript's eval() not evil?


Try: functionName.apply(context, arguments) or functionName.call(context[, argument 1, argument 2, ...]) (view reference)

Or (as a poster below mentioned) you can add the function to an object in the window namespace:

var newObj = {}; newObj.myFunction = function() { // stuff }

newObj.myFunction(); //calls the new function

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜