2
if (!window.statistics) window.statistics = {};

statistics.Update = function (var sales) {
    ...
}

在这里,我得到Unexpected token varvar sales论点的错误。我期望这样的事情是因为我不能将任何参数传递给这种类型的函数。如果我有相同的没有参数的函数类型,它就可以工作。

为什么会这样以及如何将值传递给该函数?

4

2 回答 2

4

只需删除var,您的函数就会有一个命名参数。当您调用它时(您永远不会在代码中调用它),您将在该命名参数中传递您希望它接收的任何值。

if (!window.statistics) window.statistics = {};

statistics.Update = function (sales) {
// No 'var' here -------------^

    console.log(sales);

}; // <== Off-topic: Note the semicolon

statistics.Update("foo"); // Logs "foo" to the console
于 2013-11-07T08:17:38.960 回答
1

您只需为参数命名,无需指定值。

statistics.Update = function (sales) {
    ...
}

你可以通过调用这样的方法来传递你的值:

var s = '';

statistics.Update(s);
于 2013-11-07T08:19:26.720 回答