써치킴의 우당탕탕 개발 블로그

[JS Essentials][Ch2][클래스] ES6 Classes 본문

파도파도 나오는 JavaScript

[JS Essentials][Ch2][클래스] ES6 Classes

써치킴 2022. 1. 28. 19:03

축약형 일반함수를 사용할 수 있다.

normal : function () {   ->    normal()

const searchkim = {
  name : 'SearchKim',
  // normal : function () { 
  // -> normal()
  normal() {    // 축약형 일반함수
    console.log(this.name);
  },
  arrow : () => {           // 화살표 함수
    console.log(this.name);
  }
}
searchkim.normal(); 
searchkim.arrow();

 

자바스크립트는 프로토타입 기반의 프로그래밍 언어인데

안정적이고 효율이 높은 다른 객체지향 프로그래밍 언어의 영향을 받아서 

'클래스'라는 개념을 흉내내 새로운 문법을 ES6에서 제공하기 시작했다.

/* function User(first, last) {    // 생성자 함수
  this.firstName = first;
  this.lastName = last;
}
User.prototype.getFullName = function () {        // prototype 속성에 함수를 만들어주면 메모리에 한번만 생성됨 
  return `${this.firstName} ${this.lastName}`;    // 데이터 보관
} */

class User {
  // constructor: function(first, last){ 와 같다.
  constructor(first, last){
    this.firstName = first;
    this.lastName = last;
  }
  // class를 사용하면 프로토타입 속성을 사용하지 않아도 프로토타입 메소드가 정의된다.
  getFullName(){
    return `${this.firstName} ${this.lastName}`;    // 데이터 보관
  }
}

const search = new User('Search', 'Kim');
const amy = new User('Amy', 'Kim');
const neo = new User('Neo', 'Kim');

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

class를 사용하면 프로토타입 속성을 사용하지 않아도 프로토타입 메소드가 정의된다!

Comments