最近オブジェクトの作成方法を色々と試していて、
理想としては、
- superができる
- 継承ができる
- privateが書ける
- 構造がわかりやすい
というオブジェクトができるようになればと考え、
その過程でできた作り方のひとつを忘れないようにメモ。
var parent = function(spec, my){
var my = my || {},
that = {};
my.word = "Hello! ";
that = Object.create({
say : function(){
console.log("parent:",my.word, this.name);
}
});
that.name = spec.name;
return that;
}
var child = function(spec, my){
var my = my || {},
that = Object.create(parent(spec, my)),
super_say = that.say;
that.say = function(){
my.word = "Hi! ";
super_say.apply(this);
}
return that;
}
var a = child({
name : "hoge"
});
var b = child({
name : "fuga"
});
a.say();//parent: Hi! hoge
b.say();//parent: Hi! fuga
console.log(a);
これはGoodPartsで紹介されている関数型継承を模した作り方で、
特徴としては「my」を継承間で共有できるというもの。
でも構造がわかりにくいかなと。
prototype.jsやenchant.jsで利用されているようなClass.createが一番良いかなと考え中。