通过反射形式调用javascript函数?在jquery

时间:2013-11-29 02:36:51

标签: javascript jquery ajax

所以我有这两个javascript函数:

function some_name(say_something){
    console.log('hello' + say_something);
}

call_other_fuction_after_doing_something('some_function')


// In some other file, some where - in the land of make believe.
function call_other_fuction_after_doing_something(function_name){
    $.ajax({
        url : /*Go some where*/,
    type : 'POST'
    data : { /*Some kind of data*/},
    success : function(result){
        if(function_name !== undefined){
        $.fn[success_action](result); // Pay attention to this!
        }
    },
    });
} 

因此我们可以看到我在某个文件中执行某些功能,其中一些功能会记录到控制台:" hello"然后结果是从附加到它的ajax调用返回的结果。

我认为这会有用,因为我读到了有关此here in this question的内容。但显然我错了,因为我得到的错误是:

Uncaught TypeError: Object [object Object] has no method 'some_name' 

任何想法如何做这种"反思"在javascript(jquery)?

1 个答案:

答案 0 :(得分:1)

您要做的是调用一个$.fn属性的函数,它看起来不存在。

尝试传递函数引用而不是名称

function some_name(say_something){
    console.log('hello' + say_something);
}

call_other_fuction_after_doing_something(some_name)


//In some other file, some where - in the land of make believe.
function call_other_fuction_after_doing_something(fn){
    $.ajax({
        url : /*Go some where*/,
    type : 'POST'
    data : { /*Some kind of data*/},
    success : function(result){
        if(typeof fn == 'function'){
            fn(result); // Pay attention to this!
        }
    },
    });
}