Javascript函数名称作为自执行函数中的字符串 [英] Javascript function name as a string in self executing function

查看:83
本文介绍了Javascript函数名称作为自执行函数中的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在javascript中运行一个自执行函数,不会干扰页面上的任何全局变量。我有一个字符串,其中包含我要调用的函数的名称。该函数在我的自执行函数中声明。有没有办法通过使用字符串调用该函数?

I am running a self executing function 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)

我发现:当我将其名称作为字符串时如何执行JavaScript函数

但是我的函数是自动执行而没有名字,所以我无法用窗口变量引用它。

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

推荐答案

没有全局污染并且避免使用非严格的 arguments.callee 方法。

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

基于这个答案

// 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));

这篇关于Javascript函数名称作为自执行函数中的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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