0

想象一下这样的代码:

function foo(data) {
    // ... do something with data
}

function do(userInput, callback) {
    callback(userInput);
}

function doWithReturn(userInput, callback) {
    return callback(userInput);
}

// ...
do('Hello, World', foo);
doWithReturn('Hello, World', foo);

使用普通的 do() 而不是 doWithReturn() 有什么好处吗?

我问是因为,假设我们不知道 foo() 在内部做了什么(即它可能有一个 return 语句,也许它只是触发了一个哑巴alert(data)),使用 doWithReturn 调用 foo() 总是看起来“更安全”,因为如果foo() 恰好返回一个值,不使用 doWithReturn 显然是错误的。

4

1 回答 1

0

如果一个函数返回一个值,这表明它可能很有用。我会为函数取一个名字,一旦出现某个返回值会带来好处的场景,我就会添加一个返回值。

我不知道这是否回答了你的问题。

于 2013-07-20T17:57:16.073 回答