オブジェクトを後から拡張するMixinを使いこなす
JavaScriptは柔軟な言語仕様になっているので任意のオブジェクトをPrototypeで拡張できます。hifiveで同じような機能を提供するのがMixinになります。
Mixinを使うことで、継承関係にはないようなオブジェクト同士に同じ機能を追加できるようになります。
Mininの使い方
Mixinは h5.mixin.createMixin
を使って作成します。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var mixin = h5.mixin.createMixin({ | |
set: function(p, v) { | |
this[p] = v; | |
}, | |
get: function(p) { | |
return this[p]; | |
}, | |
times: function(p, i) { | |
return this[p] * i; | |
} | |
}); |
今回は適当なオブジェクトを作ります。このオブジェクト自体にはメソッドは特にありません。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var target = { | |
hoge: 'Hello World', | |
fuga: 5 | |
}; |
そしてmixinを実行します。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
mixin.mix(target); |
これでtargetオブジェクトにメソッドが追加されました。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
> target.get('hoge') | |
–> Hello World | |
> target.times('fuga', 10) | |
–> 50 |
このようにMixinを使うことでオブジェクトの拡張が容易になります。すでにインスタンスが作られた後でも使えるので、特定のインスタンスにだけメソッドを追加することもできるでしょう。
今回のコードはJSFiddleで試せます。Mixinを使いこなすとコードが分かりやすくなりますので、ぜひ使いこなしてください。
コメントは受け付けていません。