JS Class 입문!

JS Class 입문!

출처. https://www.youtube.com/watch?v=_DLhUBWsRtw&t;=228s

오늘도 공부했당.

나 스스로한테 뿌듯한 시간이었던 듯!

오늘 공부했던 Class는 JS를 객체지향으로 바꿔주는 그런 느낌이다.

잘 모르지만...ㅎㅎ

Python의 super, JAVA의 override를 좀 더 쉽게 이해할 수 있게 된 것 같다.

// Object-oriendted programming // class: template // object: instance of class // JavaScript classes // - introduced in ES6 // - syntactical sugar over prototype-based inheritance 'use strict'; // 1. Class declarations class Person { // constructor constructor(name, age) { // fields this.name = name; this.age = age; } // methods speak() { console.log('${this.name}: hello!'); } } const JM = new Person('JM', 26); console.log(JM.name); //JM console.log(JM.age); //26 JM.speak(); //JM: hello! // 2. Getter and Setter class User { constructor(firstName, lastName, age) { this.firstName = firstName; this.lastName = lastName; this.age = age; } //값을 리턴 get age() { return this._age; } //값을 설정\ // 1. 공격적인 방법 set age(value) { if(value < 0) { throw Error('age can not be negative'); } this._age = value; } // 2. 젠틀한 방법 set age(value) { this._age = value < 0 ? 0 : value; } } //wrong property const user1 = new User('JM', 'CHOI', -1); console.log(user1.age); //-1 but age can't be negative; // 3. Field (public, private) // Too soon! class Experiment { publicField = 2; #privateField = 0; } const experiment = new Experiment(); console.log(experiment.publicField); //public한 값 console.log(experiment.privateField); //읽을 수도, 변경할 수도 없음 // 4. Static properties and methods // Too soon! class Article { static publisher = 'JM Coding'; constructor(articleNumber) { this.articleNumber = articleNumber; } static printPublisher() { console.log(Article.publisher); } } const article1 = new Article(1); const article2 = new Article(2); //static을 쓰면 .을 써서 사용할때 Class.static을 사용함. //why? 빈번하거나 고정적이게 사용되는 class에서 static하게 사용하기 때문 //들어오는 데이터에 상관없이 사용할 때 이용됨. console.log(Article.publisher); Article.printPublisher; // 5. Inheritance // a way for one class to extend another class. 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 {} class Triangle extends Shape { draw() { super.draw(); //부모의 draw를 사용!!! console.log('삼각형'); } getArea() { return (this.width * this.height) / 2; } //JS의 Object -> toString을 overridding toString() { return 'Triangle: color: ${this.color}'; } } const rectangle = new Rectangle(20,20,'blue'); rectangle.draw(); //drawing blue color of console.log(rectangle.getArea()); //400 const triangle = new Triangle(20,20,'red'); triangle.draw(); //drawing red color of //overridding을 통해 다형성 추가!!! console.log(triangle.getArea()); //200 // 6. Class checking: instanceOf // instanceOf: 왼쪽의 object가 오른쪽의 Class를 이용해서 만든 것 인지 확인 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(rectangle instanceof Object); //true, JS에서 만든 모든 object는 JS의 Object를 상속했음

getter와 setter의 개념 상속과 다형성의 개념

이건 잊지 말자!

1. Getter는 값을 리턴할 때, Setter는 값을 받아올 때 사용.

ex) age >= 0 이어야 하는데 -1을 입력한 경우에

User(-1) -> class User(age) -> constructor의 this.age -> get의 age

constructor의 = age -> set의 value로 입력 -> this.age = value < 0 ? 0 : value; 를 거쳐

this._age를 정해주고 get에서 return this._age이므로

입력 값을 한 번 걸러내 주는 역할을 한다!

2. private 한 값을 지정하는 건 앞에 #을 달아주면 된다! 하지만 ES6에서 추가됐으므로 잘 쓰지 않는다.

3. static은 class에서 빈번하게 사용되거나 입력 값에 무관하게 사용되는 것이면 사용한다.

외부에서 static을 사용할 때는 그냥 이름이 아닌 'class.이름' 으로 사용한다.

4. 상속과 다형성은 다른 언어에서도 볼 수 있는 특징인데

- 상속

class 이름 extends 참조클래스 {}

- 다형성

class 이름 extends 참조클래스 {

//참조 클래스에서 사용하는 것

draw() {

ex 1)

console.log('a');

ex 2)

return 0;

}

}

from http://it-jm.tistory.com/12 by ccl(A) rewrite - 2021-12-25 19:28:17