본문 바로가기

js

[javascript] class와 object 차이점(객체지향)

1. Class

 

fields

methods를 담을 수 있음

class안에서 함수를 선언할 때 function을 쓰지 않아도 됨

 

2. object

 

class를 이용하여 새로운 instance를 생성한 것

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

// object 생성
const hi = new Person(hi, 27);
// 새로운 object를 생성할 땐 new를 붙여줘야함

hi.speak();
// 결과 값 : hi: hello!

 

 

3. Getter & Setters

 

사용자가 지정된 범위 밖의 값을 입력하는 걸 막을 수 있음

(내가 지정한 값으로 변경되게 설정 가능)

 

get

값을 return

 

set

값을 할당

* value 꼭 넣어야 함

class User {
	constructor(firstName, lastName, age) {
    	this.firstName = firstName;
        this.lastName = lastName;
        
        this.age = age;
        // getter를 호출 -> setter를 호출
    }
    
    get age(){
    	return this._age;
        // getter와 setter안에 쓰이는 변수 이름 다르게 만들기
        // 아니면 call stack 에러 뜸
    }
    // age 값을 리턴함
    
    set age(value){
    	this._age = value;
        // 활용 this._age = value < 0 ? 0 : value;
    }
    // 리턴된 age 값을 age에 할당함
}

const user1 = new User('steve', 'job', -1);
console.log(user1.age);
// 0을 반환함

 

 

4. Public, private

 

생성자를 쓰지 않고 필드를 정의할 수 있음

class Experiment {
	publicField = 2;
    
        #privateField = 0;
        // class 내에서만 값 읽기, 변경, 적용 가능
        // 외부에서 호출하게 되면 undefined
}

 

 

5. Static

 

object(데이터)와 상관없이 class가 가지고 있는 고유의 값, 동일하게 사용되는 method 값을 저장할 때 사용

class 자체에 연결됨

 

* object와 상관없이 공통적으로 class에서 쓸 수 있는 것에 쓰면 좋음(메모리 사용을 줄여줌)

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

const article1 = new Article(1);
console.log(article1.publisher);
// undefined

console.log(Article.publisher);
// hi
// class 자체에 붙어 있기 때문

Article.printPublisher();
// hi

 

 

6. 상속 & 다양성

 

공통된 부분을 계속 재사용할 수 있음

(한 곳에서 수정하면 모든 곳이 수정돼서 유지보수 유리함)

class Shape{
	constructor(width, height, color){
    	this.width = width;
        this.heigh = height;
        this.color = color;
    }
    
    draw(){
    	console.log('${this.color} wow!');
    }
    
    getArea(){
    	return width * this.height;
    }
    
    class Rextangle extends Shape {}
    // 키워드 extends로 Shape을 연장함
    // Shape에 있는 모든 것들이 Rextangle에 포함됨
    
    class Triangle extends Shape {
    	draw(){
    		console.log('hi');
    	}
        // hi
        
        super.draw(){
    		console.log('hi');
    	}
        // 부모의 draw인 red wow! 와 hi 같이 출력됨
        
    	getArea(){
	    	return (width * this.height) / 2;
    	}
    }
    // 필요한 함수만 재정의해서 사용가능
    
    const retangle = new Rectangle(20, 20, 'blue');
    rectangle.draw();
    // blue wow!
        const triangle = new Triangle(20, 20, 'red');
    triangle.draw();
    // red wow!

 

 

7. instanceOf

 

왼쪽에 있는 object가 오른쪽에 있는 class의 instance인지 아닌지 true와 false로 알려줌

console.log(rectangle instanceof Rectangle); // true
console.log(triangle instanceof Rectangle); // false
console.log(triangle instanceof Triangle); // true
console.log(triangle instanceof shape); // true
console.log(triangle instanceof Object); // true
// 자바스크립트에서 만든 모든 object는 자바스크립트에 있는 object를 상속한 것임