개발이야기
자바스크립트 클로저 활용 예 본문
자바스크립트의 클로저의 특성을 활용하면, 자바와 같은 객체지향 언어의 캡슐화처럼 활용할 수 있다.
function Person(name, age){
var thisName = name;
var thisAge = age;
return{
getName : function() {return thisName;},
getAge : function() {return thisAge;},
setName : function(x) {thisName = x;},
setAge : function(x) {thisAge = x;}
};
}
var user = Person("hoon", 30);
console.log(user.getName()); // hoon
console.log(user.getAge()); // 30
user.setName("hwi");
user.setAge(25);
console.log(user.getName()); // whi
console.log(user.getAge()); // 25
외부에서 Person 객체의 지역변수에 직접적으로는 접근하지 못하지만, 해당 객체에 선언된 메소드를 통해서는 접근이 가능하다.
'Javascript' 카테고리의 다른 글
function의 arguments (0) | 2020.04.11 |
---|---|
외부 js/css 파일 불러올때 주의점 (0) | 2020.02.27 |
[jQuery] $+변수의 의미 (0) | 2020.02.25 |
[jQuery] jQuery 개체를 DOM 개체로 변환하기 (0) | 2020.02.23 |
[jQuery] html()과 text() 함수의 차이 (0) | 2020.02.23 |
Comments