Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Private variables with TypeScript + WeakMaps
var Number;
(function (Number_1) {
var map = new WeakMap();
var internal = function (object) {
if (!map.has(object))
map.set(object, {});
return map.get(object);
};
var Number = (function () {
function Number(x) {
internal(this)._x = x;
}
Object.defineProperty(Number.prototype, "x", {
get: function () {
return internal(this)._x;
},
set: function (x) {
console.log('wtf');
internal(this)._x = x;
},
enumerable: true,
configurable: true
});
return Number;
})();
Number_1.Number = Number;
})(Number || (Number = {}));
var myNumber = new Number.Number(4);
console.log(myNumber); // {}
console.log("Direct access " + myNumber._x); // undefined
console.log("Getter access " + myNumber.x); // 4
myNumber.x = 54;
console.log(myNumber.x); // 54
var Number;
(function (Number_1) {
let map = new WeakMap();
let internal = function (object) {
if (!map.has(object))
map.set(object, {});
return map.get(object);
};
class Number {
constructor(x) {
internal(this)._x = x;
}
get x() {
return internal(this)._x;
}
set x(x) {
internal(this)._x = x;
}
}
Number_1.Number = Number;
})(Number || (Number = {}));
var myNumber = new Number.Number(4);
console.log(myNumber); // {}
console.log(`Direct access ${myNumber._x}`); // undefined
console.log(`Getter access ${myNumber.x}`); // 4
myNumber.x = 54;
console.log(myNumber.x); // 54
module Number {
let map = new WeakMap();
let internal = function (object) {
if (!map.has(object))
map.set(object, {});
return map.get(object);
}
export class Number {
constructor(x: number) {
internal(this)._x = x;
}
get x(): number {
return internal(this)._x;
}
set x(x: number) {
internal(this)._x = x;
}
}
}
var myNumber = new Number.Number(4);
console.log(myNumber); // {}
console.log(`Direct access ${myNumber._x}`); // undefined
console.log(`Getter access ${myNumber.x}`); // 4
myNumber.x = 54;
console.log(myNumber.x) // 54
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment