5.2 JavaScript ES6 Class 기본 문법

지구·2023년 7월 20일
0

JavaScript

목록 보기
26/30
function User(first, last) {
	this.firstName = first
	this.lastName = last
}
User.prototypes.getFullName = function() {
	return `${this.firstName} ${this.lastName}`
}

const jigu = new User('jigu', 'Kim')
const neo = new User('Neo', 'Anderson')

console.log(jigu) 
console.log(neo)

위 코드처럼 prototypes 방식으로 작성한 코드를 ES6에서 새로 나온 Class방식으로 바꿔서 작성할 수 있다.

class User {
	constructor(first, last) {
		this.firstName = first
		this.lastName = last
	}
	getFullName: function() {
		return `${this.firstName} ${this.lastName}`
	}
}

const jigu = new User('jigu', 'Kim')
const neo = new User('Neo', 'Anderson')

console.log(jigu) 
console.log(neo)

첫번째 코드와 동일하게 동작한다. new라는 키워드로 함수처럼 호출해서 나온 인스턴스를 활용할 수 있다.

profile
프론트엔트 개발자입니다 🧑‍💻

1개의 댓글

comment-user-thumbnail
2023년 7월 20일

너무 좋은 글이네요. 공유해주셔서 감사합니다.

답글 달기