74

Could you please point me to the nice way of skipping optional parameters in JavaScript.

For example, I want to throw away all opt_ parameters here:

goog.net.XhrIo.send(url, opt_callback, opt_method, opt_content, {'Cache-Control': 'no-cache'}, opt_timeoutInterval)
4

3 回答 3

135

解决方案:

goog.net.XhrIo.send(url, undefined, undefined, undefined, {'Cache-Control': 'no-cache'})

你应该使用undefined而不是你想跳过的可选参数,因为这 100% 模拟了 JavaScript 中可选参数的默认值。

小例子:

myfunc(param);

//is equivalent to

myfunc(param, undefined, undefined, undefined);

强烈推荐:参数较多时使用JSON,参数列表中间可以有可选参数。看看这是如何在jQuery中完成的。

于 2011-12-02T13:22:48.687 回答
31

简短的回答

最安全的选择是undefined,并且应该几乎无处不在。但是,最终,您不能欺骗被调用的函数认为您确实省略了参数。

如果您发现自己倾向于使用null它只是因为它更短,请考虑将一个名为的变量声明_为一个不错的简写undefined

(function() { // First line of every script file
    "use strict";
    var _ = undefined; // For shorthand
    // ...
    aFunction(a, _, c);
    // ...
})(); // Last line of every script

细节

首先,要知道:

  • typeof undefined评估为"undefined"
  • typeof null评估为"object"

所以假设一个函数接受一个它期望是 type 的参数"number"。如果你提供null一个值,你给它一个"object". 语义已关闭。1

随着开发人员继续编写越来越健壮的 javascript 代码,undefined与经典的if (aParam) {...}. 如果您继续null互换使用 withundefined只是因为它们都强制转换为false.

但请注意,函数实际上可以判断参数是否实际被省略(而不是设置为undefined):

f(undefined); // Second param omitted
function f(a, b) {
    // Both a and b will evaluate to undefined when used in an expression
    console.log(a); // undefined
    console.log(b); // undefined
    // But...
    console.log("0" in arguments); // true
    console.log("1" in arguments); // false
}

脚注

  1. 虽然undefined也不是 type "number",但它的全部工作是成为一个不是真正类型的类型。这就是为什么它是未初始化变量假定的值,以及函数的默认返回值。
于 2012-08-02T17:56:01.900 回答
4

Just pass null as parameter value.

Added: you also can skip all consequent optional parameters after the last that you want to pass real value (in this case you may skip opt_timeoutInterval parameter at all)

于 2011-12-02T12:19:52.713 回答