본문 바로가기

JavaScript

자바스크립트 상속

class는 상속은 자바와 동일하게 extends를 활용해서 상속을 받는데,

function은 상속을 어떻게 받는지 오늘 알게 되었다.

 

우선 class형 상속은

Child.js

import Parent from "./Parent.js";

export default class Child extends Parent {
    FunChild() {
        console.log("Child");
    }
}

Parent.js

export default class Parent{
    FunParent(){
        console.log("Parent");
    } 
}
import Child from "./Child.js"

const child = new Child();
console.log(child);
child.FunChild();
child.FunParent();

extends 키워드로 상속이 되었다.

 

function형 상속은

Child.js

import Parent from "./Parent.js";

Child.prototype = new Parent();
export default function Child() {

    this.FunChild = () => {
        console.log("child");
    };
};

Parent.js

export default function Parent() {
    this.FunParent = () => {
        console.log("parent");
    }
}

Run.js

import Child from "./Child.js"

const child = new Child();
console.log(child);
child.FunChild();
child.FunParent();

Child.prototype = new Parent() 이런식으로 상속이 가능하였다.

 

extends 또한 prototype형식으로 구현이 되어있어서 서로 호환이 가능했다.

Child.js

import Parent from "./Parent.js";

export default class Child extends Parent{
    FunChild(){
       console.log("Child");
   } 
}

Parent.js

export default function Parent() {
    this.FunParent = () => {
        console.log("parent");
    }
}

Run.js

import Child from "./Child.js"

const child = new Child();
console.log(child);
child.FunChild();
child.FunParent();

그 반대의 경우에도 가능 합니다.

'JavaScript' 카테고리의 다른 글

자바스크립트 새로운 객체 생성 방법  (0) 2023.08.23