为什么变量名不调用我的方法

时间:2016-06-26 14:34:00

标签: javascript

当我通过变量名称调用方法时,我会继续

TypeError: window[$hello] is not a function

我一直在阅读有关堆栈溢出的其他帖子,但它似乎并没有在我的代码上工作。我不确定我在这里做错了什么。

如果有人能帮助我,我会非常感激。以下是我的代码!谢谢!

function Actions(){



    function hello(){

        alert("hello world");


    }


    (function(){

        $(document).on("change",".item-actions",function(){

            var $hello = "hello";

        window[$hello]();


        });




    })();




}

1 个答案:

答案 0 :(得分:2)

您的hello()函数是Actions()函数的本地函数,因此它不会显示在window对象上。只有全局函数在window

您可以使用自己的对象获得类似的效果:

function Actions(){

    var functions = {
        hello: function hello(){
            alert("hello world");
        },
        // more ...
    };


    (function(){

        $(document).on("change",".item-actions",function(){

            var $hello = "hello";

            functions[$hello]();
        });
    })();
}
相关问题