I have been studying some oop principles in javascript but I have some problems related to restriction of my code. In C# and Java we can easily do this kind of restrictions and see the results but in javascript I dont understand completely what is going on under the hood.
Anyway, I am trying to create a code that people can not change it outside basically. This is why I learnt that we should use local variables instead of creating object properties and by using getFunction as a method we can just read from outside.
Another approach is using "Object.defineProperty" (Getters & Setters)
All these work perfectly for primitive types but I guess we have some problem. I can not restrict my code read only. Without writing any setter methods I can change values because of the reference type feature. So how can I approach this problem ?
// Abstraction
function Circle(radius) {
this.radius = radius;
let defaultLocation = { x: 0, y: 0 };
let color = 'red';
this.getDefaultLocation = function() {
return defaultLocation;
}
this.draw = function(){
for (let key in defaultLocation) {
console.log(key, defaultLocation[key]);
}
console.log('drawn');
};
// This can be changed from outside without set(){}
Object.defineProperty(this, 'defaultLocation', {
get(){
console.log('get function');
return defaultLocation;
}
});
// This needs set(){} to be changed
Object.defineProperty(this, 'color', {
get(){
console.log('get function');
return color;
},
set(value){
color = value;
}
});
}
const circle = new Circle(10);