如何将值传递给此函数类型

How to pass a value to this function type

本文关键字:函数 类型 值传      更新时间:2023-09-26
if (!window.statistics) window.statistics = {};
statistics.Update = function (var sales) {
    ...
}

在这里,我得到了var sales参数上的错误Unexpected token var。 我希望这样的事情是因为我无法将任何参数传递给这种类型的函数。 如果我有没有参数的相同函数类型,它可以工作。

为什么会这样,如何向此函数传递值?

只需删除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

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

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

可以通过调用方法传递值,如下所示:

var s = '';
statistics.Update(s);