我试图将函数数组作为参数传递给函数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);
    }
  })
}

最佳答案

此代码的问题在于,您在forLoop中调用的函数未绑定任何内容。取而代之。

// 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.fun时,this将成为对象obj。当您将方法影响到var时,this然后成为window,因为它是该范围内的默认对象。然后,如果我们最终将该函数绑定到对象fun2并立即调用它,则this现在是对象fun2

07-24 18:59
查看更多