【问题标题】:Is there an accepted way to omit a parameter from a function/method?是否有一种可接受的方式从函数/方法中省略参数?
【发布时间】:2013-05-10 02:23:55
【问题描述】:

假设(假设)我有一个对象构造函数MyObj,它有一个这样的方法:

MyObj.prototype.method = function(x, y){
    x = x || this.x; //default value
    y = y || this.y;
}

如果我希望 x 默认为 this.x 怎么办?这是我想出的:

var object = new MyObj();
var omit = 0; //I don't think the first two
    omit = ''; // values would even default?
    omit = null;
    omit = undefined;
object.method(omit, 5);

问题是:是否存在从函数中省略参数的最佳实践或可接受的方法?

【问题讨论】:

  • undefined 看起来更干净,因为它是你根本不通过参数时得到的。但我认为undefined 的代码比omit 更明显,特别是对于偶尔的读者/维护者。

标签: javascript function object methods parameters


【解决方案1】:
MyObj.prototype.method = function(x, y){
    x = typeof x == 'undefined' ? this.x : x; //default value
    y = typeof y == 'undefined' ? this.y : y;
}

var object = new MyObj();
object.method(undefined, 5);// pass undefined

【讨论】:

  • 请注意,如果您希望 x 或 y 能够具有任何“假”值(0、“”、假等),则此方法不适合
  • @Sushil 在这种情况下,使用x === undefined 检查undefined 会更容易。
【解决方案2】:

大多数情况下,当您觉得需要定义这样的占位符时,您真正需要的是使用选项对象:

object.method({y: 5});

请注意,使用x = x || this.x; 不允许虚假值。这就是我通常这样做的原因

function method(opt) {
   var x = (opt && 'x' in opt) ? opt.x : defaultValue;
   ...
} 

当你真的需要传递一个undefined 值时,我认为undefined 是最明显的解决方案。最明显的通常意味着最容易维护。

【讨论】:

  • @alex23 嗯,使用前总是要检查的,这里没有区别。
  • (opt && "x" in opt)(或者甚至去掉opt && 部分)更有意义吗?否则你无法显式传递undefined
  • @ian 是的。没想到(这是我重复使用的旧代码)...我编辑。
  • @dystroy 有几种方法可以“检查”这样的东西,我只是想知道:)
  • @BillyMathews 我声明了对象,就像在我的示例中一样,那么是的。但是你可以在别处声明一个选项对象并重用它。
【解决方案3】:

我倾向于发现使用null 是最适合跨语言的。这只是一个偏好问题,但我更喜欢写文字 null 值,因为其他任何东西都可以在代码的其他地方定义。 (即使undefined 也可以设置为某个值。)

MyObj.prototype.method = function(x, y){
    x = x || this.x; //default value
    y = y || this.y;
}

var object = new MyObj();
object.method(null, 5);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-08-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-09
    • 2011-12-10
    • 2016-01-25
    • 2017-03-27
    相关资源
    最近更新 更多