객체지향 JavaScript - Object Oriented JavaScript
객체지향 - 하나의 모델이 되는 청사진(blueprint)를 만들고, 그 청사진을 바탕으로 한 객체(object)를 만드는 프로그래밍 패턴
Car [ blueprint ] - 카의 종류들은 Avante,Mini,Beetles [ object ]
이것을 다시 보면 Car는 class, object들은 instances라고 부른다.
ES5 클래스는 함수로 정의할 수 있습니다.
function Car(brand, name, color) {
// 인스턴스가 만들어질 때 실행되는 코드
}
ES6에서는 class라는 키워드를 이용해서 정의할 수도 있습니다.
class Car(){
constructor(brand, name, color) {
// 인스턴스가 만들어질 때 실행되는 코드
}
}
Class 함수명을 첫글자를 대문자로 만들어 줘야한다. 소문자로 되어있다면, 이상한 것이다.
new 키워드를 통해 클래스의 인스턴스를 만들어낼 수 있습니다.
let avante = new Car('hyundai', 'avante', 'black');
let mini = new Car('bmw', 'mini', 'white');
let beetles = new Car('volkswagen', 'beetles', 'red');
각각의 인스턴스는 Car라는 클래스의 고유한 속성과, 메소드를 갖습니다.
function Car(brand, model, color){
}
let avante = new Car('hyundai', 'avante', 'black')
avante
Car{}
객체지향에는 속성과 메소드라는 것이 있다. 클래스에 속성과 메소드를 정의하고, 인스턴스에서 이용합니다.
아래와 같이 객체지향 프로그래밍은, 현실 세계에 있는 것을 프로그래밍 모델을 만들고 싶을때 사용한다.
속성 | 메소드 |
brand name color currentFuel maxSpeed |
refuel() setSpeed() drive() |
Class (속성의 정의)
ES5
function Car(brand, name, color) {
this.brand = brand;
this.name = name;
this.color = color;
}
굳이 this곳에 parameter를 만들어서 만들어 준다. 그 후 아래와 같이 instance를 만들어준다.
let avante = new Car('hyundai', 'avante', 'black')
그 후에 avante.brand 를 해주면 'hyundai'가 나오는 것을 알수있다. color 보고싶으면 avante.color 하면된다.
그 후 새로운 instance를 만든다면?
let mini = new Car('bmw', 'mini', 'red')
mini.color 작성시 red가 나오는 것을 알수있다. 고유의 속성들이 표현이 되고 그런것들을 이용하는것이 this라는 것을 알수있따.
ES6
class Car() {
constructor(brand, name, color){
this.brand = brand;
this.name = name;
this.color = color;
}
}
Class (메소드의 정의)
ES5
function Car(brand, name, color) {/*생략 */ }
Car.prototype.refuel = function(){
// 연료 공급을 구현하는 코드
}
Car.prototype.drive = function(){
// 운전을 구현하는 코드
}
여기서 drive를 예로 들어서 정의를 해본다면 다음과 같다.
Car.prototype.drive = function(){
console.log(this.model + '출발!!!');
}
이렇게 되면 mini라는 것돠 avante라는 것이 등록이될수있다.
실행시 mini.drive(); 시 mini출발!!!이라는 것을 알 수 있다. 해당하는 속성값을 가져다가 사용될수있다.
ES6
class Car(){
constructor(brand, name, color ) { /*생략*/}
refuel(){
}
drive(){
}
}
let avante = new Car('hyundai', 'avante', 'black');
avante.color; // 'black'
avante.drive(); // 아반떼가 운전을 시작합니다.
let mini = new Car('bmw', 'mini', 'white' );
mini.brand; // 'bmw'
mini.refuel(); // 미니에 연료를 공급합니다.
let avante = new Car('hyundai', 'avante', 'black');
avante.color; // 'black'
avante.drive(); // 아반떼가 운전을 시작합니다.
let mini = new Car('bmw', 'mini', 'white' );
mini.brand; //'bmw'
mini.refuel();// 미니에 연료를 공급합니다.
prototype? constructor? this?
prototype | 모델의 청사진을 만들 때 쓰는 원형 객체(original form)입니다. |
constructor | 인스턴스가 초기화될 때 실행하는 생성자 함수 |
this | 함수가 실행될 때, 해당 scope마다 생성되는 고유한 실행 context(execution context) new 키워드로 인스턴스를 생성했을 때에는, 해당 인스턴스가 바로 this의 값이 됨 |
실전 예제 - 배열
[마치 배열을 사용한것 처럼 보이지 않나요?]
let avante = new Car('hyundai', ' avante', 'black');
avante.color; // 'black'
avante.drive(); // 아반떼가 운전을 시작합니다.
let arr = ['code', 'states', 'pre'];
arr.length; // 3
arr.push('course') // 새 element를 추가합니다.
arr은 class인가 instance인가? -> instance입니다.
arr의 class는? -> 대문자 Array입니다.
let arr = new Array('code', 'states', 'pre'); 이런식으로도 만들수 있다. 문법적으로 같은 것이다.
우리가 배열을 정의하는 것은 Array의 인스턴스를 만들어내는 것과 동일합니다.
mdn 메소드 설명에 prototype이라고 붙어있는 이유?
array.prototype.push() .......
앞에 죄다 prototype 붙어있는 이유는 대문자 Array에 push 구현이 원형 객체에 정의되어 있기 때문입니다.
매개변수 - Parameters 복습하기
function timeTOGoHome(speed, distance){ // 2. 매개변수(parameters)를 통해 전달받은 인자를 사용할 수 있습니다.
let time = distance / speed;
return time;
}
timeToGoHome(20, 100); // 1. 전달인자(arguments)와 함께 함수에 전달합니다.
만일, 전달인자의 길이가 유동적이라면?
Math.max(3,5,8,10); // 10
Math.max(3,5,8,10,20); // 20
Math.min(3,5,8,10,100,1000); // 3
보통 optional한 parameter를 대괄호로 표시합니다.
Math.max([값1[ 값2 [. ......]]])
위와 같은 기능을 하는,
getMaxNum([값1[, 값2[, ...]]]) 함수를 만들어 봅시다.
function getMaxNum( ){ //매개변수 어떻게 지정?
}
getMaxNum(3,5,8,10); // 10
getMaxNum(3,5,8,10,20) ; // 20
() 안에 ...nums 입력
function getMaxNum(...nums){
console.log(nums); // [3,5,8,10]
}
getMaxNum(3,5,8,10);
ES6
Rest Parameter를 이용해 매개변수를 지정해줍니다.
매개변수가 배열의 형태로 전달됩니다.
function getMaxNum(...nums){
return nums.reduce(function(acc, current){
if(acc > current){
return acc;
} else {
return current;
}
});
}
getMaxNum(3, 5, 8, 10); // 10
arguments 라는 키워드를 이용할 수도 있습니다. ES5
function getMaxNum(){
console.log(arguments); // {0:3, 1:5, 2:8, 3:10} //다만, 이 arguments 객체는 배열같아 보이지만, 배열이 아닙니다. 이를 유사배열이라고 부릅니다.
}
getMaxNum(3,5,8,10);
function getMaxNum(){
console.log(arguments); // {0:3, 1:5, 2:8, 3:10} //다만, 이 arguments 객체는 배열같아 보이지만, 배열이 아닙니다. 이를 유사배열이라고 부릅니다.
}
getMaxNum(3,5,8,10);
매개변수에 기본값을 넣어주고 싶을 경우?
ES6
Default Parameter를 할당해줄 수 있습니다.
문자열/숫자/객체 등 어떠한 타입도 가능합니다.
function getRoute(destination, departure = 'ICN'){
return '출발지 : ' + departure + ', '
+ '도착지: ' + destination;
}
getRoute('PEK'); // '출발지 : ICN, 도착지 : PEK'
매개변수에 기본값을 넣어주고 싶을 경우?
function getRoute(destination, departure = 'ICN'){
return '출발지 : ' + departure + ', ' + '도착지: ' + destination;
}
getRoute( undefined, 'PEK'); // '출발지 : ICN, 도착지 : PEK'
function getRoute(destination, departure = 'ICN'){
return '출발지 : ' + departure + ', '
+ '도착지: ' + destination;
}
getRoute( undefined, 'PEK'); // '출발지 : ICN, 도착지 : PEK'
중간에 기본 매개변수가 들어가는 경우, undefined를 넘겨줬을 때 기본값으로 처리합니다.
'Codestates > 06.15 - 07.10' 카테고리의 다른 글
2020.06.29 solo / checkpoint - 객체지향 JavaScript, Value vs. Reference (0) | 2020.06.28 |
---|---|
2020.06.29 pair / Testbuilder Step1 - Step3 (0) | 2020.06.27 |
2020.06.25 [TIL] Closure (0) | 2020.06.20 |
2020.06.25 JavaScipt Koans (0) | 2020.06.20 |
2020.06.25 [TIL] Scope (0) | 2020.06.20 |