개발공부/Javascript
6. 클래스와 오브젝트의 차이점(class vs object), 객체지향 언어 클래스 정리
MyAlice
2021. 4. 27. 14:28
728x90
** 이 글은 유튜브 강의을 보고 공부하면서 스스로 콘솔로 작성하고, 따라치면서 Javascript 기초 공부를 하는 공간입니다.
www.youtube.com/watch?v=_DLhUBWsRtw&list=PLv2d7VI9OotTVOL4QmPfvJWPJvkmv6h-2&index=6
'use strict';
// 1. Class declarations
class Person {
constructor(name, age){
this.name = name;
this.age = age;
//field
}
speak() {
console.log('${this.name} : hello!');
}
}
const ellie = new Person('ellie', 21);
console.log(ellie.name); //ellie
console.log(ellie.age); //21
ellie.speak(); //ellie: 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;
}
set age(value){
this._age = value < 0 ? 0 : value;
}
}
const user1 = new User('steve', 'Job, -1');
console.log(user1.age);
// 3.Fields (public , private)
//Too soon!
class Experiment {
publicField = 3;
#privateField = 12; //class 내에서만 접근가능하지만, 외부에서는 접근이 안됨
}
const experiment = new Experiment();
console.log(experiment.publicField); // 3
console.log(experiment.privateField); // undefined
// 4. Static properties and methods
//Too soon!
class Article {
static publisher = 'Dream coding';
constructor(articleNumber){
this.articleNumber = articleNumber;
}
static printPublisher(){
console.log(Article.publisher);
}
}
const article1 = new Article(1);
const article2 = new Article(2);
console.log(article1.publisher); //undefined
console.log(Article.publisher); //Dream coding
Article.printPublisher(); //Dream coding
//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')
}
gerArea(){
return height * this.width;
}
}
class Rectangle extends Shape {}
class Triangle extends Shape {
// 안에서 다시 재정의를 할 수 있다.
draw(){
super.draw(); //부모의 draw 도 호출 될 수 있다.
console.log('삼각형')
}
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 Triangle(20,20,'red');
triangle.draw(); //drawing red color of / 삼각형
console.log(triangle.getArea()); //200
// 6. Class checking: instance of (퀴즈!!!!!!!!!)
console.log(rectangle instanceof Rectangle);
console.log(triangle instanceof Rectangle);
console.log(triangle instanceof Triangle);
console.log(triangle instanceof Shape);
console.log(triangle instanceof Object);
//true
//false
//true
//true
//true
728x90