默认参数函数

时间:2012-10-14 14:38:01

标签: javascript

foo(a,b,c)函数参数(a,b,c)默认定义

这是我的代码:

function foo(a, b, c) {


    // a, b, c default @param ?


};

或foo(a,b,回调){}默认回调?感谢。

3 个答案:

答案 0 :(得分:4)

通常的解决方案是:

function foo(a, b, c) {
    a = a || 22;
    b = b || "ee";
    c = c || function(){};
};

如果您的参数可以有0''作为有效值,则可以测试

 if (typeof(a)=='undefined') a==22;

答案 1 :(得分:0)

CoffeeScript为此提供了很好的语法:

test = (a = 1, b = 2) ->
  console.log a, b

编译为JavaScript时:

(function() {
  var test;

  test = function(a, b) {
    if (a == null) {
      a = 1;
    }
    if (b == null) {
      b = 2;
    }
    return console.log(a, b);
  };

}).call(this);

答案 2 :(得分:-2)

它只是屈服于功能;

function foo(a, b, callback) {

    // @param defaults
    (a || (a = "default a"));
    (b || (b = "default b"));


    // if  callback not function is function() {} --> callback();
    (callback || (callback = function() { return ""}));


    console.log(a, b, callback());

};

foo(); // default a default b undefined
foo("a--", "b--", function() { return "callback"}); // a-- b-- callback

function foo(a, b, callback) {

    // @param defaults
    var a = a || "default a";
    var b = b || "default b";

    // if  callback not function is function() {} --> callback();
    var callback = callback || function() {};

    console.log(a, b, callback());
};