Skip to content

Instantly share code, notes, and snippets.

@teramako
Created October 5, 2012 05:37
Show Gist options
  • Save teramako/3838281 to your computer and use it in GitHub Desktop.
Save teramako/3838281 to your computer and use it in GitHub Desktop.
プロトタイプ内のメソッドから、そのインスタンスのプライベートな値をset/getできるようにするサンプル(WeakMapの使用)
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