코딩일상

[객체지향프로그래밍]super, prototype은 과연 언제 사용할까요? 본문

개발 공부/JavaScript

[객체지향프로그래밍]super, prototype은 과연 언제 사용할까요?

solutionMan 2022. 7. 31. 21:43
반응형

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

 

 

반응형
Comments