JS 문법 - 인스턴스

KODYwiththeK·2022년 12월 21일
0

JavaScript

목록 보기
27/32

JS 문법 - 인스턴스

Class: 제로베이스
Created: December 21, 2022 10:44 PM
Type: Javascript
강의 명: 초심자도 빈틈없이 학습하는 자바스크립트

인스턴스

클래스가 객체를 만들어내는 틀이라면, 인스턴스는 클래스나 생성자함수라는 틀에 의해 만들어진 객체를 인스턴스라고 한다.

  • 클래스나 프로토타입을 이용하여 만든 객체
  • 프로퍼티와 메소드를 상속받는다.

정적(static)

  • 객체로 접근할 수 없음
  • 클래스 명으로만 접근 가능

클래스를 선언할때 프로퍼티와 메소드 앞에 static 키워드를 작성하여 선언한다.

static property와 static method 는 객체로 접근하여 사용할 수 없다. ( obj.propery , obj.method )

클래스(클래스명)로만 접근하여 사용할 수 있다. ( Class.propery , Class.method )

어떤 객체든 상관없이 공통된 모든 객체에 같은 프로퍼티, 메서드가 필요할 때 사용하면 메모리를 줄일수 있는 이점이 있다.

예제 코드

class Article {
  static publisher = 'alice'; // Static property
  constructor(articleNumber) {
    this.articleNumber = articleNumber; // 일반적인 property
  }

  static printPublisher() { // Static methods
    console.log(Article.publisher);
  }
}

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

// bad
console.log(article1.publisher); // undefined
article1.printPublisher(); // 에러

// good
console.log(Article.publisher); // alice
Article.printPublisher(); // alice

정적 static이 붙으면, 인스턴스 명으로 접근 불가. 클래스 명으로만 가능하다.

클래스 상속

부모가 자식에게 물려주는 것

→ 부모 class 가 자식 class 에게 물려주는 것.

→ 자식 class는 부모 class 사용 가능하다.

클래스에서 다른 클래스로 상속하면서 클래스의 기능을 확장해 나갈수 있다.

상속받을 클래스를 선언할 때 extend 부모클래스 키워드를 사용하여 선언한다.

class 자식클래스 extends 부모클래스 {}

예제 코드

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;
  }
}

⇒ Shape 라는 부모 클래스 선언

class Rectangle extends Shape {} 
// Shape의 모든 정의들이 Rectangle클래스에 포함이 된다.
class Triangle extends Shape {
  getArea() {
  // 메서드 오버라이딩 - Shape에 정의되었던 메서드를 덮어씌워서 재정의한다.. 
	// 프로퍼티도 오버라이딩이 가능하다.
    return (this.width * this.height) / 2;
  }
  draw() {
    super.draw(); // super는 부모클래스, 즉 Shape클래스를 지칭한다.
    console.log(`🔺`);
  }
}

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

const triangle = new Triangle(20, 20, 'blue');
triangle.draw(); // drawing blue color of 🔺
console.log(triangle.getArea()); // 200

Rectangle클래스와 , Triangle클래스가 Shape클래스를 상속받는다.

상속받을때 프로퍼티와 메소드는 오버라이딩이 가능하다.

spuer.메서드spuer.프로퍼티 로 부모클래스의 메서드와 프로퍼티에 접근이 가능하다.

오버라이딩

자식클래스가 부모클래스를 상속받으면서 선언될 때

부모클래스의 프로퍼티와 메서드를 다시 새롭게 정의하여 덮어 씌운다.

클래스 체크 : instanceOf

객체가 클래스의 속해있는지 여부를 확인하는 용도이다.

결과는 bool이다.

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에 정의되어있는 메서드를 오버라이딩 할수도 있다.
profile
일상 속 선한 영향력을 만드는 개발자를 꿈꿉니다🧑🏻‍💻

0개의 댓글

관련 채용 정보