LoginSignup
1
1

More than 5 years have passed since last update.

JavaScriptで引数の有無でsetter/getterを切り替えるのはアリでしょうか

Posted at

つまり、setXxx/getXxxを作らずに、xxx()/xxx(arg)にしてしまう感じ。

example.js
var Hoge = (function() {
  var prop;
  return function() {
    var that = {};
    that.prop = function() {
      if (arguments.length > 0)
        prop = arguments[0];
      else
        return prop;
    };
    return that;
  };
})();

使う側はこんな感じ

use.js
var hoge = new Hoge();
hoge.prop(100);
console.log(hoge.prop()); // output 100

僕が知らないだけで、これって結構常套句だったりしますでしょうか?

1
1
2

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
1
1