Notice
Recent Posts
Recent Comments
Link
«   2025/04   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30
Tags
more
Archives
Today
Total
관리 메뉴

개발이야기

자바스크립트 클로저 활용 예 본문

Javascript

자바스크립트 클로저 활용 예

re2592 2020. 2. 25. 23:53

자바스크립트의 클로저의 특성을 활용하면, 자바와 같은 객체지향 언어의 캡슐화처럼 활용할 수 있다.

 

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 객체의 지역변수에 직접적으로는 접근하지 못하지만, 해당 객체에 선언된 메소드를 통해서는 접근이 가능하다.

Comments