객체 지향

feelslikemmmm·2020년 9월 18일
0

javascript

목록 보기
21/37
post-thumbnail

객체 지향 프로그래밍


► 하나의 모델이 되는 청사진을 만들고, (class)

 그 청사진을 바탕으로 한 객체(Object)를 만드는 instance) 프로그래밍 패턴
  • ES5 클래스는 함수로 정의할 수 있습니다
    function Car (brand, name, color) {
    	//인스턴스가 만들어질 때 실행되는 코드
    }
  • ES6 에서는 class라는 키워드를 이용해서 정의할 수도 있습니다
    class Car() {
    	constructor(brand, name, color) {
    	//인스턴스가 만들어질 때 실행되는 코드
    	}
    }

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

let avante = new Car('hyundai', 'avante', 'black');

let mini = new Car('bmw', 'mini', 'white');

let beetles = new Car('volkswagen', 'beetles', 'red');

각각의 인스턴스는 Car라는 클래스의 고유한 속성과, 메소드를 갖습니다

► 속성과 메소드

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

  • 속성
    • brand
    • name
    • color
    • currentFuel
    • maxSpeed
  • 메소드
    • 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) {/* 생략 */}
	 
		retuel() {
		}
		
		drive() {
		}
  }

► 인스턴스에서의 사용 예시

ES5
function Car(brand, name, color) {
	this.brand = brand; //이 예시에서 this는 avante와 mini를 의미함
	this.name = name;
	this.color = color;
}

let avante = new Car('hyundai', 'avante', 'black');

let mini = new Car('bmw', 'mini', 'white');

avante.color // black;
avante.name // avante;

mini.brand // bmw;

Car.prototype.drive = function () {
	console.log(this.model + '출발!');
}

avante.drive(); // avante출발!!

mini.drive(); // mini출발!!

► prototype? constructor? this?

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

► 요약

// 이 함수는 constructor(생성자)함수
// Car === class
function Car(brand, name, color) {
	this.brand = brand; //this 객체 : 이 예시에서 this는 avante와 mini를 의미함
	this.name = name;
	this.color = color;
} 
// Car.prototype = prototype 객체 : 여기에 속성이나 메소드를 정의할 수 있음
Car.prototype.drive = function () {
	console.log(this.name + '가 운전을 시작합니다');
}
//여기서 avante === instance
let avante = new Car('hyundai', 'avante', 'black');
profile
꾸준함을 잃지 말자는 모토를 가지고 개발하고 있습니다 :)

0개의 댓글