JavaScript 공부 [5. 클래스, 오브젝트, 상속, 다형성]

Min Hyung Kim·2021년 7월 26일
0

JavaScript Study!

목록 보기
5/13
post-thumbnail

class & object

class : template. 데이터의 틀이라고 생각하면 쉽다.
object: instance of a class. 데이터의 틀을 사용하여 실제로 데이터를 넣어서 만든것.
자바스크립트에는 ES6에 도입되었다.

Class 기본 예시

class Person {
	//constructor
	constructor(name, age) {
    	this.name = name;
        this.age = age;
        }
        
        //method
        speak() {
        console.log(`${this.name}: hello!`);
        }
        
}

const minbro = new Person('minbro', 25);
console.log(minbro.name);	// minbro
console.log(minbro.age);	// 25
minbro.speak();			// minbro: hello!

Getter & Setter

class의 field와 method를 캡슐화하여 사용자의 실수를 방지하고 보안을 유지한다.

class User {
	//constructor
	constructor(firstName, lastName, age) {
    	this.FirstName = FirstName;
    	this.LatsName = LatsName;
        this.age = age;
        }
        
        //method
        get age() {
        	return this._age
        }
        
        set age(value) {
        	this._age = value < 0 ? 0 : value
        }
        // 여기서 age라는 변수를 그대로 사용하면 무한루프가 발생한다.
        // value값을 age에 넣을때 setter를 다시 호출하게 된다는데 흠....
        // 공부가 더 필요한 부분이다...
}

const user1 = new User('marcus', 'kim', -9)
console.log(user1.age)		//0

상속과 다형성

Shape라는 클래스를 만들고, 이를 상속받는 Rectangle과 Triangle

class Shape{
	constructor(width, height, color) {
    	this.width = width
        this.height = height
        this.color = color
    }
    
    draw() {
    	console.log(`drawing ${this.color} color!`)
    }
    
    getArea() {
    	return this.width * this.height
    }
}

class Rectangle extends Shape {}			// 상속!!!!!
const rectangle = new Rectangle(20, 20, 'black')
rectangle.draw()					// drawing black color!
console.log(rectangle.getArea())			// 400

class Triangle extends Shape {				// 상속!!!!!
	draw() {
    	super.draw()					// 상속!!!!!
        console.log('TRIANGLE!')			// 다형성!!!
    }
	getArea() {
    	return (this.width * this.height) / 2		//overriding. 다형성!!!
    }
}
const triangle = new Triangle(20, 20, 'red')
triangle.draw()						// TRIANGLE!
							// drawing red color!
console.log(triangle.getArea())				// 200
profile
지금은 갈팡질팡하지만 점차 바르게 걷게될지어다

0개의 댓글