我一直在学习JavaScript中的面向对象编程原则,但是在代码限制方面遇到了问题。在C#和Java中,我们可以很容易地进行这种限制并查看结果,但在JavaScript中,我不完全理解内部发生了什么。
无论如何,我正在尝试创建一段代码,使人们基本上无法在外部更改它。这就是为什么我学到,我们应该使用局部变量而不是创建对象属性,并通过使用getFunction作为方法来读取值。
另一种方法是使用"Object.defineProperty"(获取器和设置器)。
所有这些对于基本类型都有效,但我想我们会遇到一些问题。如果不编写任何setter方法,则由于引用类型特性,我无法将代码仅限制为只读。那么我该如何解决这个问题?
// 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);