Movatterモバイル変換


[0]ホーム

URL:


LoginSignup
118

Go to list of users who liked

120

Share on X(Twitter)

Share on Facebook

Add to Hatena Bookmark

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

JavaScriptでメソッドチェーンを作る

Last updated atPosted at 2014-12-04

はじめに

jQueryのメソッドチェーンはとても便利で、自分もよく使っていますが「作り方」が
よく分かっていなかったので実際に簡単なサンプルを作ってみました。
知っている人にとっては簡単だと思いますが、自分のように知らない人に少しでも
お役に立てれば幸いです(`・ω・´)ゞ

元記事http://sawapi.hatenablog.com/entry/2014/12/05/004710

そもそもメソッドチェーンとは

メソッドチェーンとは、メソッドをつなげて処理することをいいます。
例えばjQueryだと、

jQuery('div').width(100).height(100).css({backgroundColor:'#000'});

といったようにwidth, height, cssのメソッドをつなげて書くことができます。
もし、jQueryがメソッドチェーンに対応していないと以下の様な形で書かないといけません。

vardiv=newjQuery('div');// 内部的にnewしてるのでつけるかどうか微妙だけど。div.width(100);div.height(100);div.css({backgroundColor:'#000'});

一度変数に入れることが必須となるので少しめんどくさいですね。

メソッドチェーンの基本的な作り方

作り方の前にまずは、文字列をappendメソッドで連結し、getメソッドで連結した文字列を取得する
メソッドチェーンに対応していないクラスを作ってみます。

varbuilder=function(str){if(typeofstr==='undefined'){this._str='';}else{this._str=''+str;// 型変換}};builder.prototype={// 文字連結append:function(str){this._str+=''+str;},// 連結した文字列を返すget:function(){returnthis._str;}}

上記のクラスを使うと

varb=newbuilder();b.append('hoge');b.append('fuga');b.append('moge');varresult=b.get();console.log(result);// > hogefugamoge

このような形で書くことになります。
さて、このbuilderクラスをメソッドチェーンできるようにしてみましょう。

varbuilder=function(str){if(typeofstr==='undefined'){this._str='';}else{this._str=''+str;// 型変換}};builder.prototype={// 文字連結append:function(str){this._str+=''+str;// 自分自身を返すreturnthis;},// 連結した文字列を返すget:function(){returnthis._str;}}

このクラスは以下のように利用することができます。

varresult=newbuilder().append('hoge').append('fuga').append('moge').get();console.log(result);// > hogefugamoge

メソッドをつなげて書くことが出来ました!
どこが変わったかというと、appendメソッドで「return this;」として自分自身を返してあげています。
これだけでメソッドチェーンに対応できるんですね!
ただし、これではbuilderの前にnewがついてしまっています。newを取る方法はいろいろあるような
気がしますが、ここではjQueryのやり方にならって書いてみます。

「new」を取る

では、実際にnewをつけない書き方で書いてみましょう。

varbuilder=function(str){// インスタンスをbuilderの中で生成returnnewbuilder.prototype.init(str);};builder.prototype={// 初期化メソッド( initという名前じゃなくてもいいです )init:function(str){// コンストラクタ的なのをbuilder.prototype.initの中に書くif(typeofstr==='undefined'){this._str='';}else{this._str=''+str;// 型変換}},// 文字連結append:function(str){this._str+=''+str;// 自分自身を返すreturnthis;},// 連結した文字列を返すget:function(){returnthis._str;}}// builder.initのprototypeにbuilderのprototypeを持たせるbuilder.init.prototype=builder.prototype;

これでnewをつけずに書くことができます!

varresult=builder().append('hoge').append('fuga').append('moge').get();console.log(result);// > hogefugamoge

ポイントとしては、builderの中で書いていたコンストラクタ的な処理を自身のprototypeの中に
作った関数( ここではinit )にやらせてしまい、その関数のprototypeにbuilderのprototypeを
持たせ、builderの中でインスタンスを生成することでnewを省略することができます。
さて、ここまで分かったところで簡単な電卓クラスを作ってみます。

簡易電卓クラス

たす、ひく、かける、わるのできる簡単な電卓クラスを作ります。
ただし、カッコのついた計算もできるように少し工夫します。

!function(window){// 簡易電卓クラス// 3 * ( 1 + 3 ) / 6// みたいな式を// calc( 3 ).multiply( calc( 1 ).plus( 3 ) ).divide( 6 ).get();// こんな感じで使えるようにvarcalc=function(num){// calcクラスであればそのまま返すif(numinstanceofcalc){returnnum;}// 数字以外は0にするif(typeofnum!=='number'){num=0;}// インスタンス生成returnnewcalc.prototype.init(num);}calc.prototype={// コンストラクタinit:function(num){this._num=num;},// たすplus:function(num){this._num+=calc(num).get();returnthis;},// ひくminus:function(num){this._num-=calc(num).get();returnthis;},// かけるmultiply:function(num){this._num*=calc(num).get();returnthis;},// わる( 0でわることを考慮してない )divide:function(num){this._num/=calc(num).get();returnthis;},// 取得get:function(){returnthis._num;}}// initのprototypeにcalcのprototypeをつっこむcalc.prototype.init.prototype=calc.prototype;window.calc=calc;}(window);

さて、このクラスを使って簡単な計算をしてみましょう。

// 10 + 20calc(10).plus(20).get();// > 30// ( 9 - 7 ) * 5calc(9).minus(7).multiply(5).get();// > 10// 3 * ( 1 + 3 ) / 6// 括弧内の計算はcalcでおこないそのオブジェクト自体を引数に指定するcalc(3).multiply(calc(1).plus(3)).divide(6).get();// > 2

ちょっと工夫すると括弧付きの計算もできるようになりました!

まとめ

メソッドチェーンするには、メソッドの最後に「return this;」とつけて自分自身を返すことで
簡単に作ることができました。使いどころはライブラリとか作らない限りあまりないかもしれませんが覚えておいて損はなさそうです!
calc.jsをgistにあげました。

118

Go to list of users who liked

120
2

Go to list of comments

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
118

Go to list of users who liked

120

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?


[8]ページ先頭

©2009-2025 Movatter.jp