ES6 Classes 패턴

lbr·2022년 7월 10일
0

ES6 Class

시작하기 앞서..

const heropy = {
  name: 'Heropy',
  //normal: function () {
  //	console.log(this.name);
  //}
  normal() {
  	console.log(this.name);
  }
  arrow: () => {
  	console.log(this.name);
  }
}

heropy.normal();
heropy.arrow();
  • 객체데이터 내부에서 일반함수를 사용할 때에는 : function을 생략해 줄 수 있습니다.

class라는 키워드를 이용하여 바꾸기

JavaScript는 prototype 기반의 프로그래밍 언어인데, 좀 더 안정적이고 신뢰도가 높은 다른 객체 지향 언어들에 영향을 받아서 class라는 개념을 흉내내서 새로운 문법을 ES6에서 제공하기 시작했습니다.

//function User(first, last) {
//  this.firstName = first;
//  this.lastName = last;
//}
//User.prototype.getFullName = function () {
//  return `${this.firstName} ${this.lastName}`;
//}

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


const heropy = new User('Heropy', 'Park');
const amy = new User('Amy', 'Clarke');
const neo = new User('Neo', 'Smith');

console.log(heropy);
console.log(amy.getFullName());
console.log(neo.getFullName());

생성자 함수와 prototype 부분의 코드를 간결하고 직관적이고, 유연한 새로운 문법으로 작성할 수 있습니다.

0개의 댓글