Created
October 5, 2012 05:37
-
-
Save teramako/3838281 to your computer and use it in GitHub Desktop.
プロトタイプ内のメソッドから、そのインスタンスのプライベートな値をset/getできるようにするサンプル(WeakMapの使用)
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
var TestClass = (function(){ | |
var _map = new WeakMap; // private variables | |
function TestClass() {} | |
Object.defineProperty(TestClass.prototype, "name", { | |
configurable: true, | |
get: function () { | |
return _map.has(this) ? _map.get(this).name || null : null; | |
}, | |
set: function (val) { | |
var m = _map.has(this) ? _map.get(this) : {}; | |
m.name = val; | |
_map.set(this, m); | |
} | |
}); | |
return TestClass; | |
}()); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment