10d_객체 지향 프로그래밍

doggoddog·2020년 8월 30일

일일 정리

목록 보기
14/34

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');

avante //Car{}

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

속성 : class의 속성
eg. brand, name, color, currentFuel, maxSpeed
메소드 : Car라는 클래스를 통해서 하고자하는 액션
eg. refuel(), 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) { 생략 }
Car.prototype.refuel=function(){
연료 공급을 구현하는 코드
}
Car.prototype.drive=function(){
운전을 구현하는 코드
}

ES6
class Car(){
constructor(brand, name, color){ 생략 }
refuel(){
}
drive(){
}
}

-prototype? constructor? this?

prototype : 모델의 청사진을 만들 때 쓰는 원형 객체(original form)
constructor : 인스턴스가 초기화될 때 실행하는 생성자 함수
this : 함수가 실행될 때, 해당 scope마다 생성되는 고유한 실행 context (execution context)
new 키워드로 인스턴스를 생성했을 때에는, 해당 인스턴스가 바로 this의 값이 됨

예제에서는 avante===this
Car : class
function Car(~ ~this.color = color;} : constructor(생성자) 함수
Car.prototype. : prototype 객체: 여기에 속성이나 메소드를 정의할 수 있음

실전예제-배열
let arr = ['code', 'states', 'pre'];
let arr = new Array('code', 'states', 'pre');
위 두개가 똑같은 의미

arr.length //속성
arr.push //메소드

mdn 메소드 설명에 prototype이라고 붙어있는 이유
push 구현이 원형 객체에 정의되어 있기 때문 //Array.prototype.push()

profile
----------------------------

0개의 댓글