복습 #6 매개변수와 객체지향 프로그래밍

Joshua Song / 송성현·2019년 11월 19일
0

프리코스_35

목록 보기
11/15

Parameter & Argument

먼저 매개변수(parameters)와 전달인자(arguments)의 차이를 알아본다.

function change (price, moneypaid) {
  return moneypaid - price
};

위 함수에서 price와 moneypaid는 매개변수이다.


function change (100, 150);

숫자를 넣은 위 함수에서 100과 150은 전달인자다.

이렇게 상황에 따라서 이름이 바뀐다.

Rest Parameter

전달인자가 만약 하나가 아닌 여러 가지라면? 유동적이라면? ...을, Rest Parameter 써주면 된다.

예제를 위해 Math.min의 역할을 하는 함수를 짜보겠다.


function minimum (...nums) {

  return nums.reduce( function (prev, cur) {
    if (prev > cur){
      return cur

    }

    else {
      return prev;

    }

  });

}

위 함수는 reduce를 사용해 가장 작은 숫자를 찾는건데 ...nums 같은 Rest Parameter를 사용하면 매개변수가
배열의 형태로 전달된다. 이 방법은 ES6부터 가능하고, ES5에서는 arguments를 매개변수로 사용하는데 배열이 아닌 유사배열이기 때문에 array method를 사용할 수 없다.


function what(){

  console.log(arguments)

}

what (1, 3, 4, 5);

//{0:1, 1:3, 2:4, 3:5} 유사배열을 반환한다. 

Rest Parameter에 대해서 배웠고 다음은 Default Parameter다. 처음에 기본 값을 가지고 시작하고 싶다면 처음에 할당을 해주면 된다. 문자, 숫자, 객체까지 다 할당이가능하다.


function change (price, moneypaid = 200) {
  return moneypaid - price
};

change(50); 

// 150

change(50, undefined);

// 150. undefined로 그 순서에 맞춰서 넣어줘도 default parameter로 계산한다. 

OOP

매개변수를 알아봤으니 이제 객체지향 프로그래밍을 알아볼 차례이다.

  • 객체지향을 간단하게 요약하자면 하나의 모델되는 blueprint를 만들고 그걸 바탕으로 여러 객체 (object)를 만드는 것이다. 여기서 blueprintclass, 객체는 instance이다.

예를들어,

class가 function car (color) {} 라면

instance 는

let bmw = new car ("blue");

let avante = new car ("white");

등등 이다.

ES5 에서는 function car (brand, name, color) {} 식으로 class를 만들어줘야 했지만,
ES6 부터는 class 키워드로도 만들 수 있다.

class car {

  constructor (brand, name, color){

  }//인스턴스가 만들어질 때 실행될 코드

} 

클래스를 만들 때 속성과 method를 정의하면 instance에서 사용할 수 있다.

속성의 예는 brand, color, name 같은 것이고,

method의 예는 refuel(), drivewithcruise() 등이다.

속성을 세팅할때는 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;

  }

} 

Method를 세팅할때도 비슷한 구조이다.


ES5)

function car (brand, name, color) {

  car.prototype.refuel = function  () {}

  car.prototype.drivewithcruise = function () {} 

}



ES6)

class car {

  constructor (brand, name, color){ 
  }
  refuel () {
  }
  drivewithcruise () {
  }  
} 



Example)

let bmw = new car (benz, li750, black);

bmw.brand; // benz

bmw.name; //li750



bmw.refuel() //연료 충전!

bmw.drivewithcruise() //크루즈 모드~

용어를 정리하자면 prototype은 원형 객체로 모든 instance들의 blueprint라고 보면 된다.

instance는 prototype을 바탕으로 만드는 여러가지 모델? 이라고 보면 된다.

constructor는 class를 만들 때 사용하는 생성자 함수이다. 인스턴스가 초기화 될 때 사용한다.

this

this는 상황에 따라 바뀌는 실행 context 인데 여기서는 new 키워드로 생성하는 instance가 this 의 값이 된다.

마지막으로 이해하기 쉬운 example을 소개하자면,


let example = new Array(1, 3, 5);

example.length; //3

example[0]; //1



example.pop(); //[1, 3];

MDN의 나오는 array의 method들도 이미 배열의 원형 객체에 생성이 돼있어 작동하는 것이다.

끝!

profile
Grow Joshua, Grow!

0개의 댓글