JavaScript : Class

백광호·2020년 10월 22일
0

my--note

목록 보기
15/17

ES6 에서 추가된 객체 지향 언어 중 하나로
기존에 이용하던 객체 지향 언어의 방식을 크게 바꾼 방법이다.

class는 일종의 template에 속하며 이 template을 이용해
데이터를 넣어 만드는 것이 object이다

이런 class가 없었을 때에는 함수를 이용해 객체를 만들어 사용했었다.

Class 선언 및 object 생성

class를 선언하는 방법은 아래 예제를 보면 쉽게 이해할 수 있다.

class Person {
	//constructor
	constructor(name, age) {
		// fields
		this.name = name;
		this.age = age;
	}

	//method
	speak() {
		console.log(`${this.name}: hello!`);
}

// ocject
const pangho = new person('pangho', 25);

console.log(pangho.name);
console.log(pangho.age);
pangho.speak();

// 결과값으로는 pangho, 25, pangho: hello!가 출력된다.

class를 이용해 Person이라는 class를 만들고
constructor를 사용해 object를 만들 때 사용할 데이터를 전달한다
그리고 이 데이터는 this라는 fields 안에 하나씩 할당한다.

여기에 함수(method)도 추가할 수 있다.

이렇게 만들어진 class를 object로 생성할 때에는
항상 new로 시작해 class name(Person)과 데이터를 넣어주면 된다.

getter와 setters

object 작성 시 실수로 잘못 입력한 데이터를
기준에 맞게 바꿔줄수 있도록 도와주는 코드이다.

class User {
	constructor(firstName, lastName, age) {
		this.firstName = firstName;
		this.lastName = lastName;
		this.age = age;
}

	get age() {
		return this._age
	}

	set age(value) {
		this._age = value < 0 ? 0 : value;
	}
}

const user1 = new User('Steve', 'job', -1);
console.log(user1.age);

위 예시에서 유저 데이터 중 Stevejob의 나이를
실수로 -1로 적어두었다.

하지만 get을 정의하여 age를 호출해 this._age로 출력하고
set을 정의해 age의 value를 호출해 value를 0으로 변경 후
this._age의 변수로 지졍한 것을 알 수 있다.

이렇게 하면 age값이 0보다 작을때는 무조건 0으로 나오게 할 수 있다.

Class의 상속

하나의 class에서 사용한 코드를 다른 class에서도 동일하게 사용한다면
class의 코드를 상속시켜 사용할 수 있다.

class Shape {
	constructor(width, height, color) {
	this.width = width;
	this.height = height;
	this.color = color;
	}
	
	draw() {
		console.log (`deawing ${this.color} color!`)
	}

	getArea() {
	return this.width * this.height;
	}
}

class Rectangle extends Shape {}
const rectangle = new Rectangle(20, 20, 'blue');
rectangle.draw();

// 결과 값은 drawing blue color!

위 예시를 보면 Shape에서 정의한 class 코드를
Rectangle에서 extends를 사용해 상속 시킨 것을 알 수 있다.
때문에 object를 만들 때 Rectangle class를 사용해도
Shape class와 동일한 값을 얻을 수 있다.

이런 방식은 class의 재사용을 용이하게 만들어
코드를 짜거나 유지보수를 쉽게 해줄 수 있는 장점이 있다.

class Shape {
	constructor(width, height, color) {
	this.width = width;
	this.height = height;
	this.color = color;
	}
	
	draw() {
		console.log (`deawing ${this.color} color!`)
	}

	getArea() {
	return this.width * this.height;
	}
}

class Rectangle extends Shape {}
class Triangle extends shape {
	getArea() {
		return (this.widht * this.height) /2;
	}
}
const rectangle = new Rectangle(20, 20, 'blue');
rectangle.draw();
const triangle = new Rectangle(20, 20, 'red');
console.log (triangle.getArea());

// 결과값은 200

위의 class Triangle의 경우 Shape의 class를 상속 받았지만
추가로 getArea를 반으로 나눈 것을 알 수 있다.

이렇게 상속받은 class 중 필요한 함수만
재정의해서 사용할 수 있는 다양성을 가지고 있다.
이렇게 재정의 하는 것을 overwrithing라고 한다.

다만, 이렇게 재정의한 함수는
부모의 함수를 제거하고 정의하게 되는데
부모의 함수를 남기면서 재정의 하고자 한다면
super을 사용하면 된다.
super를 사용할 때에는 항상 상속자 내에서만,
this.를 사용하기 전에만 사용할 수 있다.

Class 확인하기

사용할 변수가 어떤 class를 이용하고 있는지
확인하는 방법으로 instanceof를 사용하는 것으로 알 수 있다.

instanceof를 사용하면 좌항의 값이
우항의 class를 사용하고 있는지 boolean값으로 표시해준다.

주의해야할 점은 어떤 class든 Object와 비교하면 true값이 나온다.

console.log(rectangle instanceof Rectangle);
console.log(triangle instanceof Rectangle);
console.log(triangle instanceof Triangle);
console.log(triangle instanceof Shape);
console.log(triangle instanceof Object);

// 결과값은 ture, false, true, true, true

위 예시를 예로 들어 instanceof를 사용해았다.
여기서 마지막 triangle의 instanceof 의 class를 Object로 입력해도
결과값이 true로 출력되는 것을 알 수 있다.

profile
안녕하세요

0개의 댓글

관련 채용 정보