this를 이용해서 값을 설정해주면 Student.name과 같은 식으로 직접 접근이 가능하다. 이를 방지하기 위해 자바스크립트에서는 아래와 같은 방식으로 캡슐화를 해준다.
function Rectangle(w, h) {
let width = w;
let height = h;
this.setWidth = function(w){
width = w;
};
this.getWidth = function(){
return width;
};
this.getHeight = function(){
return height;
}
}
Rectangle.prototype.getArea = function(){
return this.getWidth() * this.getHeight();
}
var rectangle = new Rectangle(5, 6);
rectangle.setWidth(10);
console.log(rectangle.getArea());
캡슐화된 객체의 변수는 set, get 메소드를 구현해 이를 통해 간접 접근해주면 된다.