2016-01-29 34 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

相關問題