Created
January 15, 2013 07:35
-
-
Save kawanet/4536942 to your computer and use it in GitHub Desktop.
JavaScript property lazy build lazy initialization getter method
This file contains 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
var seq = 0; | |
var Foo = function () { | |
this.seq = ++ seq; | |
}; | |
var Bar = function () { | |
this.fooB = new Foo(); | |
}; | |
Bar.prototype = { | |
fooA: new Foo(), // shared | |
get fooC() { | |
return this._fooC = this._fooC || new Foo(); // lazy build | |
} | |
}; | |
var bar1 = new Bar(); | |
var bar2 = new Bar(); | |
var bar3 = new Bar(); | |
console.log('bar1', bar1.fooA.seq, bar1.fooB.seq, bar1.fooC.seq); // 1 2 5 | |
console.log('bar3', bar3.fooA.seq, bar3.fooB.seq, bar3.fooC.seq); // 1 4 6 | |
console.log('bar2', bar2.fooA.seq, bar2.fooB.seq, bar2.fooC.seq); // 1 3 7 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
2013-01-12
JavaScript プロパティ lazy build 遅延初期化 getter メソッド
http://kawanet.hatenablog.com/entries/2013/01/12