[TIL] 2020-04-02 (목)

Jay Kim·2020년 4월 2일
0

Today I Learned

목록 보기
2/7

1. 스코프(Scope)

변수 접근 규칙에 따른 유효 범위


2. 클로저(Closure)

외부 함수의 변수에 접근할 수 있는 내부 함수. 또는, 이러한 작동 원리를 일컫는 용어

클로저 함수 안에서는

  • 지역 변수
  • 외부 함수의 변수
  • 전역 변수

의 접근이 전부 가능하다.

커링

함수 하나가 n개의 인자를 받는 대신, n개의 함수를 만들어 각각 인자를 받게 하는 방법

function adder(x) {
  return function(y) {
    return x + y;
  }
}

x의 값을 고정해놓고 재사용할 수 있다.

외부 함수의 변수가 저장되어 마치 템플릿 함수와 같이 사용 가능

function htmlMaker(tag) {
  let startTag = '<' + tag + '>';
  let endTag = '</' + tag + '>';
  return function(content) {
    return startTag + content + endTag;
  }
}

let divMaker = htmlMaker('div');
divMaker('Hello');  // '<div>code</div>'
divMaker('world');  // '<div>states</div>'

let h1Maker = htmlMaker('h1');
h1Maker('Headline');  // '<h1>Headline</h1>'

클로저 모듈 패턴

변수를 scope 안쪽에 가두어 함수 밖으로 노출시키지 않는 방법

function makeCounter() {
  let privateCounter = 0;
  
  return {
    increment: function() {
      privateCounter++;
    },
    decrement: function() {
      privateCounter--;
    },
    getValue: function() {
      return privateCounter;
    }
  }
}

let counter1 = makeCounter();
counter1.increment();
counter1.increment();
counter1.getValue();  // 2

let counter2 = makeCounter();
counter2.increment();
counter2.decrement();
counter2.increment();
counter2.getValue();  //  1

3. 객체지향 JavaScript(Object Oriented JavaScript)

하나의 모델이 되는 청사진(blueprint)를 만들고, 그 청사진을 바탕으로 한 객체(object)를 만드는 프로그래밍 패턴

  • 청사진(blueprint) -> class
  • 청사진을 바탕으로 한 객체(object) -> instance
// class
function Car(color) {}

// instances
let avante = new Car('blue');
let grandeur = new Car('black');
let sonata = new Car('silver');

[~ES5] 클래스는 함수로 정의할 수 있다.

function Car(Brand, name, color) {
  // 인스턴스가 만들어질 때 실행되는 코드
}

[ES6~] class라는 키워드를 이용해서 정의할 수도 있다.

class Car() {
  constructor(brand, name, color) {
  	// 인스턴스가 만들어질 때 실행되는 코드
  }
}

new 키워드를 통해 클래스의 인스턴스를 만들어낼 수 있다.

클래스에 속성과 메소드를 정의하고, 인스턴스에서 이용힌다.

1) 클래스: 속성의 정의 [this 키워드]

// ES5
function Car(brand, name, color) {
  this.brand = brand;
  this.name = name;
  this.color = color;
}

// ES6
class Car() {
  constructor(brand, name, color) {
    this.brand = brand;
    this.name = name;
    this.color = color;
  }
}

2) 클래스: 메서드의 정의 [prototype]

// ES5
function Car(brand, name, color) { /* 생략 */ }
Car.prototype.refuel = function() {
  // 연료 공급을 구현하는 코드
}
Car.prototype.drive = function() {
  // 운전을 구현하는 코드
}

// ES6
class Car() {
  constructor(brand, name, color) { /* 생략 */ }
  
  refuel() {
    // 연료 공급을 구현하는 코드
  }
  drive() {
    // 운전을 구현하는 코드
  }
}

prototype - 원형 객체(original form)

모델의 청사진을 만들 때 쓰는 원형 객체
여기에 속성이나 메서드를 (추가로) 정의할 수 있음

constructor - 생성자 함수

인스턴스가 초기화될 때 실행하는 생성자 함수

this

함수가 실행될 때, 해당 scope마다 생성되는 고유한 실행 컨텍스트(execution context). new 키워드로 인스턴스를 생성했을 때에는 해당 인스턴스가 바로 this의 값이 됨

배열(array)의 class는 'Array 객체'

우리가 배열을 정의하는 것은 Array의 인스턴스를 만들어내는 것과 동일하다.


4. 매개변수(Parameter)

function timeToGoHome(speed, distance) {  
        // 2) 매개변수(parameters)를 통해 전달받은 인자를 사용할 수 있음.
  let time = distance / speed;
  return time;
}

time ToGoHome(20, 100);
// 1) 전달인자(arguments)와 함게 함수에 전달

전달인자(arguments)의 개수가 유동적이라면?

Rest Parameter(...)를 이용해 매개변수를 지정해준다. (ES6~)

매개변수가 배열의 형태로 전달된다.

function getMaxNum(...nums) {
  console.log(nums);  // [1, 3, 5, 7, 9]
}

getMaxNum(1, 3, 5, 7, 9)

위를 참고하여 Math.max() 과 같은 메서드를 만들어보면

function getMaxNum(...nums) {
  return nums.reduce(function(acc, cur) {
    if(acc > cur) {
      return acc;
    } else {
      return cur;
    }
  });
}

getMaxNum(1, 3, 5, 7, 9);  // 9

arguments라는 키워드를 이용한다.(~ES5)

function getMaxNum() {
  console.log(arguments);  // {0: 1, 1: 3, 2: 5, 3: 7, 4: 9}
}                          // 유사배열
getMaxNum(1, 3, 5, 7, 9);

매개변수에 기본값을 넣어주고 싶을 경우?

Default Parameter를 할당해줄 수 있다.(ES6~)

문자열/숫자/객체 등 어떠한 타입도 가능하다.

function getRoute(destination, departure = 'ICN') {
  return '출발지: ' + departure + ', '
       + '도착지: ' + destination;
}

getRoute('PEK');  // '출발지: ICN, 도착지: PEK'

중간에 기본 매개변수가 들어가는 경우, undefined를 넘겨줬을 때 기본값으로 처리한다.

function getRoute(departure = 'ICN', destination) {
  return '출발지: ' + departure + ', '
       + '도착지: ' + destination;
}

getRoute(undefined, 'PEK');  // '출발지: ICN, 도착지: PEK'
profile
minuzai

0개의 댓글