클로저

leehowook·2022년 5월 19일
0

클로저는 독립적인 (자유) 변수를 가리키는 함수이다.
또는, 클로저 안에 정의된 함수는 만들어진 환경을 ‘기억한다’.
일반적으로 함수 내에서 함수를 정의하고 사용하면 클로저라고 한다.

function getClosure() {
  var text = 'variable 1';
  return function() {
    return text;
  };
}

var closure = getClosure();
console.log(closure()); // 'variable 1'

위에서 정의한 getClosure()는 함수를 반환한다.
반환된 함수는 getClosure() 내부에서 선언된 변수 text를 참조하고 있다.
참조된 변수는 함수 실행이 끝났다고 해서 사라지지 않고, variable 1을 반환하고 있다.

getClosure()에서 반환된 함수를 클로저라고 한다.

클로저를 통한 은닉화

JavaScript에서 객체지향 프로그래밍을 말한다면 Prototype을 통해
객체를 다루는 것을 말한다. ES2015에는 클래스도 있다.

Prototype을 통한 객체를 만들 때의 주요한 문제 중 하나는
Private variables에 대한 접근 권한 문제이다.

function Hello(name) {
  this._name = name;
}

Hello.prototype.say = function() {
  console.log('Hello, ' + this._name);
}

var hello1 = new Hello('김지');
var hello2 = new Hello('삼지');
var hello3 = new Hello('부지');

hello1.say(); // 'Hello, 김지'
hello2.say(); // 'Hello, 삼지'
hello3.say(); // 'Hello, 부지'
hello1._name = 'anonymous';
hello1.say(); // 'Hello, anonymous'
=====================================
function hello(name) {
  var _name = name;
  return function() {
    console.log('Hello, ' + _name);
  };
}

var hello1 = hello('김지');
var hello2 = hello('삼지');
var hello3 = hello('부지');

hello1(); // 'Hello, 김지'
hello2(); // 'Hello, 삼지'
hello3(); // 'Hello, 부지'

Hello()로 생성된 객체들은 모두 name이라는 변수를 가지게 된다.
변수명 앞에 underscore()를 포함했기 때문에 일반적인 JavaScript
네이밍 컨벤션을 생각해 봤을때 이 변수는 Private variable으로
쓰고싶다는 의도를 알 수 있다. 하지만 외부에서 쉽게 접근가능한 변수일 뿐이다.

특별히 인터페이스를 제공하는 것이 아니라면, 여기서는 외부에서
_name에 접근할 방법이 전혀 없다. 이렇게 은닉화도 생각보다 쉽게 해결할 수 있다.

출처 : https://itns3200.tistory.com/93

profile
be higher

0개의 댓글