4
4

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.

オブジェクト作成方法

Last updated at Posted at 2012-11-29

最近オブジェクトの作成方法を色々と試していて、
理想としては、

  • 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が一番良いかなと考え中。

4
4
0

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?