简体   繁体   English

在JavaScript中调用/触发匿名函数的正确方法?

[英]Correct way(s) to call/trigger an anonymous function in JavaScript?

Let's say I have this function, which is like a different version of and utilizes Array.push with some different logic inside it: 假设我有此函数,它类似于的另一个版本,并利用Array.push及其内部的一些不同逻辑:

var array_values = [];

function pump_array(needle, haystack, callback) {
    var pushed = false;

    if(haystack.indexOf(needle) === -1) {
        haystack.push(needle);
        pushed = true;
    }

    if(typeof callback == 'function') {
        callback(haystack, pushed);
    }
}

And now if I we use it in this manner: 现在,如果我们以这种方式使用它:

var pump_array_callback = function(new_data_in_array_values, pushed) {
    if(pushed) {
        console.log('added "first" into "array_values[]"');
    } else {
        console.log('"first" already in "array_values[]"');
    }

    console.log(new_data_in_array_values);
};

pump_array('first', array_values, pump_array_callback);
pump_array('first', array_values, pump_array_callback);

The first function call of pump_array will output: pump_array的第一个函数调用将输出:

added "first" into "array_values[]"

And second will do the opposite: 第二个则相反:

"first" already in "array_values[]"

So basically, my question is: 所以基本上,我的问题是:

Is this the right way to call/execute an anonymous function in a function, or elsewhere: 这是在函数或其他地方调用/执行匿名函数的正确方法:

if(typeof callback == 'function') {
    callback(haystack, pushed);
}

And are there any other methods of doing the same, in a more pragmatic way? 还有其他更实用的方法吗?

Your invocation of the callback is fine. 您对回调的调用很好。

And are there any other methods of doing the same, in a more pragmatic way? 还有其他更实用的方法吗?

You should not use a callback at all for this use case. 在此用例中,您根本不应使用回调。 Just use a return value when you can (and you hardly ever need a callback). 只要有可能就使用返回值(并且几乎不需要回调)。

function pump_array(needle, haystack) {
    if (haystack.indexOf(needle) === -1) {
        haystack.push(needle);
        return true;
    }
    return false;
}

var array_values = [];
function pump_array_result(pushed) {
    if (pushed) {
        console.log('added "first" into "array_values[]"');
    } else {
        console.log('"first" already in "array_values[]"');
    }
    console.log(array_values);
};

pump_array_result(pump_array('first', array_values));
pump_array_result(pump_array('first', array_values));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM