如何将函数(委托?)作为参数传递给Javascript中的另一个函数,然后使用它

时间:2012-06-23 14:12:45

标签: javascript jquery function delegates

我想将一个函数传递给另一个函数。我认为像这样传递的函数是调用委托人吗?我很难在网上找到这种事情的好解释。这是正确的方法吗?

function getCellContentByColumnIndex = function(row, index) {
    return $(row.children().get(index)).text();
}
function naturalSort(a, b, func) {
    //...
    var $a = func(a);
    var $b = func(b);
    //...
}

//usage  
naturalSort(x, y, getCellContentByColumnIndex);

4 个答案:

答案 0 :(得分:6)

您的代码:

function getCellContentByColumnIndex = function(row, index) {
    return $(row.children().get(index)).text(); 
}

语法错误。以下是函数声明:

functon foo() {}

这是一个函数表达式:

var foo = function(){}

这是一个命名的函数表达式:

var foo = function bar(){}

这里有很多不同的答案,文章Named function expressions demystified中有一个详细的解释,它也涵盖了函数声明和表达式的许多其他方面。

术语“匿名函数”是一个函数表达式的术语,它没有名称,也没有赋值给任何东西,例如。

someFn( function(){...} )

调用someFn并传递一个没有名称的函数。可以在someFn中为其分配名称。 Ic可以被引用为arguments[0]

传递一个函数不是委托,这是将侦听器放在父元素上并捕获冒泡事件的行话的行话,在它可以替换表示每个单元格上的单击侦听器的情况下,它是首选的桌上的单个听众。

无论如何,传递函数就像传递任何其他对象一样:

function foo(){
  alert('foo');
}

function callIt(fn) {
  fn();
}

callIt(foo);  // 'foo'

在上文中,foo传递给callIt并分配给本地变量fn,然后被调用。

答案 1 :(得分:3)

您将函数作为变量传递,如下所示:

var getCellContentByColumnIndex = function(row, index) {
    return $(row.children().get(index)).text();
}

function naturalSort(a, b, func) {
    //...
    var $a = func(a);
    var $b = func(b);
    //...
}

//usage  
naturalSort(x, y, getCellContentByColumnIndex);

这是使用匿名函数调用的。

答案 2 :(得分:2)

匿名函数..

var getCellContentByColumnIndex = function(row, index) {
    return $(row.children().get(index)).text();
}

将会有效。在你的代码中,调用的东西已经很完美.. :)

答案 3 :(得分:1)

在JavaScript中,函数被视为一等公民,这意味着你可以像简单的变量一样把它们扔在那里。关键是,当你想引用函数时使用FunctionName并使用FunctionName()来调用它。

这一行:naturalSort(x, y, getCellContentByColumnIndex);

本来可以写成

naturalSort(x, y, function (){
    return $(row.children().get(index)).text();
});

在这种情况下,它将被称为传递匿名函数