Last active
August 8, 2016 07:31
-
-
Save kkeeth/d22d99eb957d974f39c4527be6fecec8 to your computer and use it in GitHub Desktop.
JavaScriptのデザインパターンのデモコード
This file contains hidden or 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
| // 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