2016-01-29 37 views
0

我想将函数数组作为参数传递给函数x,然后在函数x中执行它们。我也会以某种方式传递参数,但一些参数只在函数x中初始化。 传递函数数组作为参数,对于函数中的每个函数运行函数

一些功能包括了诸如:

_showData(data,type); 
console.log(data); 
$('#loading').remove(); 

这里有一个例子:

// Called somewhere else 
runFunctions([$('.dashboard').remove, $('.screen-loading').remove]); 

var runFunctions = function(functions){ 
    // do some things 
    for (var i = 0; i < functions.length; i++){ 
    functions[i](); 
} 

任何想法?

编辑: 对不起,我刚刚意识到程序不知道对象是什么,因为我用ajax调用来改变范围。

var runFunctions = function(functions){ 
    $.ajax({ 
    method: "POST", 
    url: "php/database.php", 
    dataType: "JSON", 
    data: {type:type}, 
    success: function(data, type){ 
     for (var i = 0; i < functions.length; i++){ 
     functions[i](); 
     } 
    } 
    }) 
} 

这个什么:

_accessDatabase( 
    function(onSuccess){ 
     $('.dashboard').remove(); 
     var type = 'home'; 
     _showData(data,type); // it doesn't know what data is, how can I pass it through? 
     $('.screen-loading').remove(); 
    } 
); 


var _accessDatabase = function(onSuccess){ 
    $.ajax({ 
    method: "POST", 
    url: "php/database.php", 
    dataType: "JSON", 
    data: {}, 
    success: function(data){ 
     onSuccess(data); 
    } 
    }) 
} 

我想通过VAR数据到的onSuccess功能,我该怎么办呢?

解决了:

var _request_successful = function onSuccess (data){ 
    console.log("running onSuccess"); 
    $('.dashboard').remove(); 
    var type = 'home'; 
    _showData(data,type); 
    $('.screen-loading').remove(); 
} 

_accessDatabase(_request_successful); 


var _accessDatabase = function(onSuccess){ 
    $.ajax({ 
    method: "POST", 
    url: "php/database.php", 
    dataType: "JSON", 
    data: {}, 
    success: function(data){ 
     onSuccess(data); 
    } 
    }) 
} 

回答

1

这段代码的问题是,你在for循环中调用函数未绑定到任何东西。取而代之。

// Called somewhere else 
runFunctions([ 
    $('.dashboard').remove.bind($('.dashboard')) 
, $('.screen-loading').remove.bind($('.screen-loading')) 
]); 

function runFunctions(functions){ 
    // do some things 
    for (var i = 0; i < functions.length; i++){ 
    console.log("running") 
    functions[i](); 
    } 
} 

你可以做的却是这样的:

function call(method, objs) { 
    objs.forEach(function (obj) { 
    obj[method]() 
    }) 
} 
call('remove', [$('.dashboard'), $('.screen-loading')]) 

这里的工作小提琴:https://jsfiddle.net/ogfgocp4/

要解释一下它是如何工作的,我不知道到底是内部的JavaScript ,但是当你这样做时:$('.dashboard').remove,它会返回你remove函数。如果你马上叫它,它将被绑定到给你方法的对象。如果你将它影响到其他东西,那么它将被绑定到它被调用的对象。

这里有一小段代码可以很好地解释它。

var obj = { 
    fun: function() { 
    console.log(this) 
    } 
} 
var fun2 = { 
    a: 1 
} 

//this -> obj 
obj.fun() 

// this -> window 
fun = obj.fun 
fun() 

// this -> fun2 
fun2.fun = obj.fun 
fun2.fun() 

当你调用obj.funthis将对象obj。如果将方法影响到var,this,则会变为window,因为它是此范围内的默认对象。然后,如果我们最终将函数绑定到对象fun2并立即将其调用,则this现在是对象fun2

+0

我可能误解了你的答案,但不应该将参数以相反的方式传递给你的'call'函数吗? –

+1

@FrankFajardo是的,我刚刚醒来...没有喝我的咖啡:( –

+0

我得到一个错误:未捕获TypeError:obj [方法]不是函数 – ChickenFeet

相关问题