3

関数を別の関数に渡したい。そのように渡される関数は呼び出しデリゲートだと思いますか?私はこの種のことについての良い説明をオンラインで見つけるのに苦労しています。これはこれを行う正しい方法ですか?

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

4 に答える 4

7

Your code:

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

Is a syntax error. The following is a function declaration:

functon foo() {}

And this is a function expression:

var foo = function(){}

And this is a named function expression:

var foo = function bar(){}

There are a number of answers here on the differences, there is a detailed explanation in the article Named function expressions demystified which also covers many other aspects of function declarations and expressions.

The term "anonymous function" is jargon for a function expression that has no name and isn't assigned to anything, e.g.

someFn( function(){...} )

where someFn is called and passed a function that has no name. It may be assigned a name in someFn, or not. Ic could just be referenced as arguments[0].

Passing a function is not delegating, that is jargon for the practice of putting a listener on a parent element and catching bubbling events, it is preferred in cases where it can replace say a click listener on every cell in a table with a single listener on the table.

Anyhow, passing a function is just like passing any other object:

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

function callIt(fn) {
  fn();
}

callIt(foo);  // 'foo'

In the above, foo is passed to callIt and assigned to the local variable fn, and is then called.

于 2012-06-23T14:31:23.957 に答える
4

次のような変数として関数を渡します。

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);

これは無名関数を使用して呼び出されます。

于 2012-06-23T14:15:57.077 に答える
2

匿名関数..

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

動作します..呼び出しの残りのものはすでにあなたのコードで完璧です..:)

于 2012-06-23T14:15:32.910 に答える
1

JavaScriptでは、関数は第一級市民として扱われます。つまり、単純な変数のように、関数をあちこちに投げることができます。重要なのは、関数を参照するときにFunctionNameを使用し、FunctionName()を使用してそれを呼び出すことです。

この行:naturalSort(x, y, getCellContentByColumnIndex);

次のように書くことができます

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

その場合、匿名関数の受け渡しと呼ばれます

于 2012-06-23T14:24:14.727 に答える