LoginSignup
4
5

More than 5 years have passed since last update.

引数はオブジェクトで渡したいが、普通に順番に並べて渡したりもしたい

Last updated at Posted at 2014-01-11
  • APIとしては基本的に引数はオブジェクトで渡したい
  • 必須の引数が1個とか2個のときにはオブジェクトで渡すのは面倒
  • 内部的にはオブジェクトで渡されると面倒

という感じで試行錯誤してみたらこんなかんじに。
getParamsJavaScript - 関数の引数名を取得する - Qiita [キータ]から借りました。

function getArguments(args, propertyNames) {
  if (Object.prototype.toString.call(args[0]) === '[object Object]') {
    var params = args[0];
    return propertyNames.map(function(name) {
      return params[name];
    });
  } else {
    return args;
  }
}

function defun(propertyNames, fn) {
  if (typeof propertyNames === 'function') {
    fn = propertyNames;
    propertyNames = getParams(fn);
  }
  return function() {
    return fn.apply(this, getArguments(arguments, propertyNames));
  };
}

var foo = defun(['a', 'b', 'c'], function(a, b, c) {
  console.log(a, b, c);
});

foo(1, 2, 3);
foo({a: 1, b: 2, c: 3});

var bar = defun(function(a, b, c) {
  console.log(a + b + c);
});

bar(3, 4, 5);
bar({a: 6, b: 7, c: 8});

最近話題のSweet.jsでマクロ化してしまうというのありかもしれません。

4
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
5