LoginSignup
0

More than 5 years have passed since last update.

メソッドを無理やりメソッドチェーンにする

Posted at

実装

Object.prototype.chain = function(method) {
  this[method].apply(this, Array.prototype.slice.call(arguments, 1));
  return this;
};

最後のthisthis.valueOf()でもいいかも知れません。

使い方

document.body.appendChild(
  document.createElement("a")
    .chain("setAttribute", "href", "http://qiita.com/")
    .chain("setAttribute", "target", "_blank")
    .chain("setAttribute", "id", "link")
    .chain("appendChild", document.createTextNode("Qiita"))
    .chain("addEventListener", "click", function() {
      //うんたらかんたら
    }, false)
);

使い道が思いつかない… (´・ω・`)
withでいいような気もする。

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
0