LoginSignup
11
12

More than 5 years have passed since last update.

JavaScriptでPrototype Pattern

Last updated at Posted at 2013-06-14

メモ代わり

GoF曰く→既存のオブジェクトのコピーであるテンプレートを元にオブジェクト生成を行うこと

  • jsで実装が簡単(もともとprototypeベースだし)
  • jsで継承を簡単に実装出来る。
  • 継承の実行時には関数のコピーを生成するのではなく、参照が作成される
  • わかりやすい(個人的に)

以下が例

prototype.js

var myCar = {
    name: "Ford Escort",
    drive: function(){
        console.log("I'm driving!");
    },

    panic: function(){
        console.log("Wait, How do you stop this thing?");
    }

};

// 車のインスタンスを作成するためにObject.createを利用
var yourCar = Object.create(myCar);

console.log(yourCar.name); // Ford Escort

// Object.createは第二引数でオブジェクトのプロパティを初期化出来る

var vehicle = {
    getModel: function(){
        console.log( "The model of this vehicle is…" + this.model );
    }
}

var car = Object.create(vehicle, {
    id: {
        value: MY_GLOBAL.nextId(),
        // default:  writable: false, configurable: false
        enumerable: true
    },

    model: {
        value: "Ford",
        enumerable: true
    }

});


// Object.createを使わずに実装する場合
// しかしこのやり方だと読み取り専用プロパティを生成出来ない
// vehiclePrototypeは書き換えられる可能性がある(defineProperties使えばいい?)

var vehiclePrototype = {
    init: function(carModel){
        this.model = carModel;
    },

    getModel: function(){
        console.log("The model of this vehicle is " + this.model);
    }
};

function vehicle(model){
    function F(){};
    F.prototype = vehivlePrototype;

    var f = new F();

    f.init(model);
    return f;
}

var car = vehicle("Ford Escort");
car.getModel();

// こういう感じにも実装できる
var beget = (function(){
    function F(){};

    return function(proto){
        F.prototype = proto;
        return new F();
    }
})();

var car = beget(vehiclePrototype);
car.init("hoge");
car.getModel();  // The model of this vehicle is hoge




11
12
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
11
12