IT/WILT

[JavaScript] 6. 객체지향 언어, class VS object

KimCookieYa 2022. 2. 22. 12:12

 

1. Object-oriented programming (객체지향 언어)

 - class : template, declare once, no data in

 - object : instance of a class, created many times, data in

 - JavaScript classes (introduced in ES6) : syntactical sugar over prototype-based inheritance

 

 

2. Class declarations

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

const a = new Person('apple', 20);
console.log(a.name);
console.log(a.age);
a.speak();

 

 

3. Getter & Setter

class User {
	constructor(firstName, lastName, age) {
    	this.firstName = firseName;
        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', 'Jobs', -1);
console.log(user1.age);

 

 

4. Fields (public, private)

- encapsulation(캡슐화)

class Experiment {
	publicField = 1;
    #privateField = 2;
}

const experiment = new Experiment();
console.log(experiment.publicField); // 1
console.log(experiment.privateField); // undefined

 

 

5. Static properties & methods

class Article {
	static publisher = 'Dream Coding';
    constructor(articleNumber) {
    	this.articleNumber = articleNumber;
    }
    
    static printPublisher() {
    	console.log(Article.publisher);
    }
}

const art1 = new Article(1);
console.log(art1.publisher); // undefined
console.log(Article.publisher); // Dream Coding
Article.printPublisher();

 

 

6. Inheritance & Overriding

 - a way for one class to extend another class.

clss Shape {
	constructor(width, height, color) {
    	this.width = width;
        this.height = height;
        this.color = color;
    }
    
    draw() {
    	consolo.log(`drawing ${this.color} color of`);
    }
    
    getArea() {
    	return width * this.height;
    }
}

class Rectangle extends Shape {}
class Triangle extends Shape {
	draw() {
    	super.draw();
        console.log('^');
    }
	getArea() { 								// Overriding
    	return (this.width * this.height) / 2;
    }
}

const rectangle = new Rectangle(20, 20, 'blue');
rectangle.draw();
const triangle = new Triangle(20, 20, 'red');
triangle.draw();

 

 

7. Class checking : instanceof

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