on
객체지향 프로그래밍 - Class,상속,Super
객체지향 프로그래밍 - Class,상속,Super
클래스는 생성자함수와 마찬가지로 객체를 생성하는 기능을 하고 있다. (객체 공장)
생성자 함수에서는 {}안에 초깃값을 작성했다면
class 는 constructor() 이란 함수 안에다 초깃값을 작성한다.
class 내부에서 Constructor는 한 개만 존재할 수 있으며, 2번 이상 사용 시 Syntax Error가 발생할 수 있다.
// 생성자함수로 객체 생성 function Person(name, first, second, third){ this.name=name; this.first=first; this.second=second; } Person.prototype.sum = function(){ return 'prototype : '+(this.first+this.second); } var kim = new Person('kim', 10, 20); //클래스로 객체 생성 class Person{ constructor(name, first, second){ this.name = name; this.first = first; this.second = second; } } var kim = new Person('kim', 10, 20);
Class 메소드 사용하기
생성자 함수에서는 객체명.prototype.함수명 으로 메소드를 만들어서 모든 객체가 메소드를 공유했다면
클래스에서는 class안에다 바로 메소드를 생성한다.
기능은 객체명.prototype.함수명 으로 만든 메소드와 동일하다.
특정 객체의 메소드를 수정하고 싶으면
객체가 할당된 변수.메소드 = function() {}
으로 수정한다.
class Person{ constructor(name, first, second){ this.name = name; this.first = first; this.second = second; } //메소드 생성 sum(){ return 'prototype : '+(this.first+this.second); } } var kim = new Person('kim', 10, 20); // 특정 객체 메소드 수정하기 kim.sum = function(){ return 'this : '+(this.first+this.second); } var lee = new Person('lee', 10, 10);
상속(extends)
특정 객체의 메소드를 수정하고 싶으면 객체가 할당된 변수.메소드 = function() {} 로 수정이 가능하다고 했다.
하지면 메서드를 수정할 객체가 여러개라면?
그럴때는 class의 상속 개념을 이용한다.
상속을 사용하면 하위 속성이 상위 속성에 접근이 가능하다.
문법은 아래와 같다.
class 객체 extends 상속 받고픈 객체
(지금 객체는 상위 객체의 확장판이다! 라고 외우면 편할듯)
<상속 예시>
class Person{ constructor(name, first, second){ this.name = name; this.first = first; this.second = second; } sum(){ return this.first+this.second; } } class IntroducePerson extends Person{ // 상속 결과로 Person class에 있는 this.name을 사용할 수 있다. introduce() { return `제 이름은 ${this.name} 입니다.` } } var yujin = new IntroducePerson('yujin',11,12) console.log(yujin.introduce()) // 결과값 : 제 이름은 yujin 입니다.
super 사용하기
만약 기존 클래스 값에 추가적으로 하위 클래스만 사용하고 싶은 값이 있을 때 는 super을 사용한다.
super을 사용하여 부모 객체가 가지고 있는 모든 메서드들을 호출한다.
class Person{ constructor(name, first, second){ this.name = name; this.first = first; this.second = second; } sum(){ return this.first+this.second; } } // IntroducePerson 클래스는 like 값도 받고 싶어!! 그럴 때 super이 필요함 class IntroducePerson extends Person{ constructor(name, first, second, like){ // super을 이용해서 부모객체의 모든것을 호출한다. super(name, first, second) // 부모객체에 없는 프로퍼티를 추가한다. this.like = like; } introduce() { return `제 이름은 ${this.name} 이고 좋아하는것은 ${this.like} 입니다` } } var yujin = new IntroducePerson('yujin',11,12,'puppy') document.write(yujin.introduce()) // 결과값 : 제 이름은 yujin 이고 좋아하는것은 puppy 입니다
https://ordinary-code.tistory.com/22
https://opentutorials.org/module/4047/24614
from http://liyang.tistory.com/136 by ccl(A) rewrite - 2021-10-21 23:01:54