일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 | 31 |
- typescript
- nest.js
- 기록
- array
- CS
- 자바스크립트
- 알고리즘
- 리눅스
- 네트워크
- WIL
- mongo
- next.js
- 회고
- 생각로그
- 생각일기
- mysql
- Git
- js
- til
- 생각정리
- Java
- mongoose
- 주간회고
- 트러블슈팅
- javascript
- react
- 피드백
- MongoDB
- Grafana
- 코테
- Today
- Total
코딩일상
[객체지향프로그래밍]super, prototype은 과연 언제 사용할까요? 본문
2줄 요약
super 자식이 부모가 가지고 있지 않는 객체 또는 메소드를 추가 할때
prototype 부모가 가지고있지 않는 객체 또는 메소드 를 부모한테 추가할경우
Super
Super를 사용하지 않고
자식요소인 PersonPlus가 부모요소인 Person이 가지고 있지 않는 third라는 생성자와 메소드를 추가 할 경우
Super를 사용하고
자식요소인 PersonPlus가 부모요소인 Person이 가지고 있지 않는 third라는 생성자와 메소드를 추가 할 경우
class Person{
constructor(name, first, second){
this.name = name;
this.first = first;
this.second = second;
}
sum(){
return this.first+this.second;
}
}
class PersonPlus extends Person{
constructor(name, first, second, third){
super(name, first, second);
this.third = third;
}
sum(){
return super.sum()+this.third;
}
avg(){
return (this.first+this.second+this.third)/3;
}
}
var kim = new PersonPlus('kim', 10, 20, 30);
console.log("kim.sum()", kim.sum());
console.log("kim.avg()", kim.avg());
Super
prototype을 사용하지 않고
자식요소인 PersonPlus가 부모요소인 Person이 가기조 있지 않는 third라는 생성자와 메소드를 추가 할 경우
function Person(name, first, second, third){
this.name=name;
this.first=first;
this.second=second;
}
var kim = new Person('kim', 10, 20);
kim.sum = function(){
return 'this : '+(this.first+this.second);
}
var lee = new Person('lee', 10, 10);
lee.sum = function(){
return 'this : '+(this.first+this.second);
}
console.log("kim.sum()", kim.sum());
console.log("lee.sum()", lee.sum());
prototype을 사용하고
자식요소인 PersonPlus가 부모요소인 Person이 가기조 있지 않는 third라는 생성자와 메소드를 추가 할 경우
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);
kim.sum = function(){
return 'this : '+(this.first+this.second);
}
var lee = new Person('lee', 10, 10);
console.log("kim.sum()", kim.sum());
console.log("lee.sum()", lee.sum());
객체 지향언어의 특성이 상속과 관련된
자바스크립트의 기능인 super와 prototype에 대해 공부해보았다.
레퍼런스
prototype - JavaScript 객체 지향 프로그래밍
수업소개 JavaScript의 prototype이 필요한 이유와 prototype을 통해서 코드의 재사용성과 성능을 향상시키는 방법을 알려드립니다. 강의1 prototype이 필요한 이유를 소개합니다. 강의2 prototype을 이용
opentutorials.org
super - JavaScript 객체 지향 프로그래밍
수업소개 서브(자식) 클래스에서 상위 클래스를 호출할 때 사용하는 super 키워드를 소개합니다. 강의 코드 class.js (변경사항) class Person{ constructor(name, first, second){ this.name = name; this.first = first; thi
opentutorials.org
'개발 공부 > JavaScript' 카테고리의 다른 글
[JavaScript] 진법 변환 (0) | 2022.11.10 |
---|---|
[객체지향프로그래밍]this 란?? (0) | 2022.08.04 |
JavaScript의 ES5/ES6 문법 차이!! (0) | 2022.07.24 |
JavaScript의 ES란? (0) | 2022.07.24 |
유사배열과 배열의 차이는 무엇 일까요? (0) | 2022.07.22 |