Skip to content

Instantly share code, notes, and snippets.

@kkeeth
Last active August 8, 2016 07:31
Show Gist options
  • Select an option

  • Save kkeeth/d22d99eb957d974f39c4527be6fecec8 to your computer and use it in GitHub Desktop.

Select an option

Save kkeeth/d22d99eb957d974f39c4527be6fecec8 to your computer and use it in GitHub Desktop.
JavaScriptのデザインパターンのデモコード
// simple code
// the instance is public
function Earth(){
// 既存のインスタンスの有無をチェック
if (typeof Earth.instance === "object"){
return Earth.instance;
}
this.name = "Earth";
this.age = "4.7+E9"; // 地球の寿命は47億年
// キャッシュする
Earth.instance = this;
return this;
}
// using closure
// the instance is private
function Earth(){
var instance;
Earth = function Earth() {
return instance;
};
// プロトタイププロパティを引き継ぐ
Earth.prototype = this;
// インスタンス
instance = new Earth();
// コンストラクタのポインタを再設定
instance.constructor = Earth;
instance.name = "Earth";
instance.age = "4.7+E9"; // 地球の寿命は47億年
return instance;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment