JavaScript ) class (ES6)

윤보라·2023년 2월 9일

자바스크립트

목록 보기
9/11

class를 이용해서 상속기능을 구현해보자.

1. constructor 만드는 법

class parent {
	constructor(){
    	this.name = "bora";
    }
}

const child = new parent();

// class로 부모함수의 이름 지정 후 안쪽에 constructor를 만들어주기

2. 함수 추가하는 방법

1) constructor 자체에 만들기

: 자식들이 직접 함수를 가지게됨

class parent {
	constructor(){
    	this.name = "bora";
        this.sayHi = function(){console.log("Hi")} // 이렇게
    }
}

2) constructor 바깥에 만들기

: 부모의 prototype에만 추가됨

class parent {
	constructor(){
		this.name = "bora";
	}
	sayHi(){ 				// 이렇게
		console.log("Hi")  
	} 
}

3. 파라미터 추가하는법

: constructor에 추가해주면 됨

class parent {
	constructor(name, age){ // 이렇게
		this.name = name;
      	this.age = age;
	}
	sayHi(){ 				
		console.log("Hi")  
	} 
}

const child = new parent("bora", 29);

참고 ) 프로토타입 출력하기

프로토타입을 출력할 때, a.__proto__ 말고 Object.getPrototypeOf(a)로도 확인 가능하고, 훨씬 직관적이라 쓰기 편함.

profile
Front-End 개발자

0개의 댓글