JS

Class

RRS_SH 2023. 2. 16. 01:06

이 JavaScript는 드림코딩 자바스크립트 기초강의를 보며 정리한 자료 입니다.

https://www.youtube.com/@dream-coding 

 

https://www.youtube.com/@dream-coding

 

www.youtube.com


 

연관있는 데이터를 모아놓은 컨테이너 형태이다. 속성(field)과 행동(method)으로 구성되어 있다. 메소드 없이 필드로만 이루어진 것은 데이터 클래스라고 한다. 클래스는 객채를 만들기위한 틀, 청사진이다. 그리고 그 틀을 이용, 데이터를 넣어서 만든 것이 Object 이다.

  • class: template
  • object: instance of a class
  • JavaScript classes
    - introduced in ES6
    - syntactical sugar over prototype-based inheritance
ES6에서 추가 된 Class는 기존 function으로 object를 만드는 프로토타입을 베이스로 문법만 추가된 것이다.

 

Class declarations

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

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

const tom = new Person('tom', 34);
console.log(tom.name); // tome
console.log(tom.age); // 34
tom.speak(); // tom: hello!

 

 

Getter & Setter

Class User {
	constructor(firstName, lastName, age) {
    	this.firstName = firstName;
        this.lastName = lastName;
        this.age = age;
    }
    
    get age() {
    	return this._age;
    }
    
    get age(value) {
 		//this._age = value;

 		if(value < 0) {
        	throw Error('age can not be negative');	
        }
        or
        this._age = value < 0 ? 0 : value;
	} 

    /*
    클래스 인스턴스에 데이터를 할당하거나 호출할때 메모리의 데이터를 바로 호출하거나, 
    할당하지 않고  getter, setter를 먼저 호출 한다. 
    그때에 무한정으로 계속 반복 호출되어 call stack full이 나는 에러가 발생할 수 있기 
    때문에 변수명에 '_'를 붙여 조금 다르게 사용한다.
    */
}

 

 

Fields(public, private)

class Experiment {
	publicField = 2; // 외부에서 값 접근 가능하다.
    #privateField = 0; // class 외부에서 접근 불가능하다.
    
    // 자바에서 배우는 캡슐화라고 이해 하자
}
추가 된지 얼마 안되 사용하는 개발자가 많이 없다지만(2020.04.27) 현재는 어떨지(2023.02.16)... 

 

Static

class Article {
	static publisher = 'Drummer';
    constructor(articleNumber) {
    	this.articleNumber = articleNumber;
    }
    
    static printPublisher() {
    	console.log(Article.publisher);
    }
    
    // 클래스와 연결 하여 사용 한다는 것은 알겠으나... 이해는 안됨
}

 

상속 & 다형성

Inheritance

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

class Rectangle extends Shape {} // extends로 Shape를 상속한다.

class Triangle extends Shape {
    // 다형성: 필요한 부모 함수를 재정의 할 수 있다. 이를 오버라이딩이라고 한다.
    getArea() { 
    	return (this.width * this.height) / 2;
    }
} 

const rectangle = new Rectangle(20, 20, 'blue'); 
rectangle.draw(); // drawing blue color of
console.log(rectangle.getArea()); // 400

const Triangle = new Rectangle(20, 20, 'red'); 
Triangle.draw(); // drawing red color of
console.log(rectangle.getArea()); // 200(재정의한 매소드 호출)

 

Instanceof

왼쪽의 오브젝트가 오른쪽 오브젝트로 만들어 졌는지 확인 한다.
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
// JS의 모든 오브젝트들은 Object를 상속하고 있다.(이는 JAVA와 동일하다.)