In Javascript I can create a property of object with get/set methods :
function Field(arg){
var value = arg;
// Create a read only property "name"
Object.defineProperty(this, "value", {
get: function () {
return value;
},
set: function () {
console.log("cannot set");
}
});
}
var obj = new Field(10);
console.log(obj.value); // 10
obj.value = 20; // "cannot set"
Setting value
property is disallowed here.
In TypeScript if I want to achieve the same behaviour I would have to do this (as suggested by get and set in TypeScript):
class Field {
_value: number;
constructor(arg) {
this._value = arg;
}
get value() {
return this._value;
}
set value() {
console.log("cannot set");
}
}
var obj = new Field(10);
console.log(obj.value); // 10
obj.value = 20; // "cannot set"
obj._value = 20; // ABLE TO CHANGE THE VALUE !
console.log(obj.value); // 20
But the problem as you see here is that the so-called private property _value
can be accessed/changed by the user directly without going through get/set methods for value
. How do I restrict the user from accessing this property (_value
) directly?