-
2020/09/18 -TIL (JavaScript 객체 지향)Develop/JavaScript 2020. 9. 18. 14:32
오늘 했던 일
- JavaScript 객체 지향
Javascript 객체 지향
객체 지향이란?
하나의 모델이 되는 청사진(blueprint)을 만들고, 그 청사진을 바탕으로 한 객체(object)를 만드는 프로그래밍 패턴.
여기서 청사진은 class, 청사진을 바탕으로 생성된 객체를 instance라고 한다.
class 선언
ES5
function Car(brand, name, color){ // class 이름의 앞글자는 대문자로 선언한다. // 인스턴스가 만들어질 때 실행되는 코드 }
ES6
class Car { constructor(brand, name, color) { // 인스턴스가 만들어질 때 실행되는 코드 } }
instance 생성
let sonata = new Car('현대', '소나타', 'black'); let s500 = new Car('벤츠', 's500', 'white'); let k5 = new Car('기아', 'k5', 'blue'); //각각의 인스턴스는 Car라는 클래스의 고유한 속성과, 메소드를 갖습니다.
속성과 메소드
클래스에 속성과 메소드를 정의하고, 인스턴스에서 이용합니다.
속성 메소드 brand
name
color
speedrefuel()
setSpeed()
drive()속성의 정의
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; } }
메소드의 정의
ES5
function Car(brand, name, color) { this.brand = brand; this.name = name; this.color = color } Car.prototype.drive = function() { console.log(`${this.name}가 출발합니다.`) } Car.prototype.refuel = function() { console.log(`${this.name}에 연료를 공급합니다.`) }
ES6
class Car { constructor(brand, name, color) { this.brand = brand; this.name = name; this.color = color; } drive() { console.log(`${this.name}가 출발합니다.`) } refuel() { console.log(`${this.name}에 연료를 공급합니다.`) } }
instance에서의 매소드 사용
let sonata = new Car('현대', '소나타', 'black'); sonata.color; // 'black' sonata.drive(); // 소나타가 출발합니다. let k5 = new Car('기아', 'k5', 'blue'); k5.brand; // '기아' k5.refuel(); // k5에 연료를 공급합니다.
prototype : 모델의 청사진을 만들 때 사용하는 원형 객체
constructor : 인스턴스가 초기화될 때 실행하는 생성자 함수.
this : 함수가 실행될 때, 해당 scope마다 생성되는 고유한 실행 context,
new 키워드로 인스턴스를 생성할 땐 해당 인스턴스가 this값이 된다.
'Develop > JavaScript' 카테고리의 다른 글
2020/10/01 - TIL (this, call, apply, bind) (0) 2020.10.01 2020/09/25 -TIL (고차함수, 배열 메소드) (0) 2020.09.25 2020/09/10 - TIL (Array, Object) (0) 2020.09.11 2020/09/08 - TIL (조건문, 문자열) (0) 2020.09.08 [JavaScript] 3. var, let, const의 차이 (0) 2020.09.08