JavaScript Class 알아보기

JavaScript Class 알아보기

개념정리

Class : 객체를 만들기 위한 템플릿(function 처럼 중복을 방지하기 위해 태어남)

Point! 객체를 자주 만들기 위해서 형식을 제공해줘서 중복을 방지하기 위한 템플릿

Class가 필요한 이유

Code

const firstDeveloper = { name: 'Lion', age: 22, part: 'Back-End', programLanguage: ['JavaScript', 'Node.js'] } const twoDeveloper = { name: 'Jane', age: 21, part: 'Front-End', programLanguage: ['JavaScript'] } ...

반복되는 객체(여기서는 ~Developer)를 만들 때 코드의 길이가 길어지고, 중복이 많아진다.

(name, age, part 같은 key가 중복!)

Class가 존재하지 않았을 때 (ES5)

Code

// Function으로 Class 생성 function Developer(name, age, part, programLanguage) { this.name = name; this.age = age; this.part = part; this.programLanguage = programLanguage; } // Class 사용 const firstDeveloper = new Developer('Lion', 22, 'Back-End', ['JavaScript', 'Node.js']); const twoDeveloper = new Developer('Jane', 21, 'Front-End', ['JavaScript']); ...

객체를 사용하기 전보다 first, twoDeveloper 객체를 만드는데 걸리는 코드의 길이가 1줄로,

Class를 사용하기 전보다 코드의 길이가 줄어들었다.

Class를 사용하게 되면 좋은점 (ES6)

Code

// Class 생성 class Developer{ constructor(name, age, part, programLanguage) { this.name = name; this.age = age; this.part = part; this.programLanguage = programLanguage; } } // Class 사용 const firstDeveloper = new Developer('Lion', 22, 'Back-End', ['JavaScript', 'Node.js']); const twoDeveloper = new Developer('Jane', 21, 'Front-End', ['JavaScript']); ...

함수로 Class를 만들기 보다 ES6 버전부터 개발자들이 알아 보기 쉽게

Class라는 선언문이 생겨나게 되어, 최신 문법을 사용하는게 좋다.

자세한 이유는 아래 Part를 한 번 보도록하죠.

Function 대신 Class를 사용해야 하는 이유가 무엇일까?

Code - Function

// Function // Function으로 Class 생성 function Developer(name, age, part, programLanguage) { this.name = name; this.age = age; this.part = part; this.programLanguage = programLanguage; } // Class 상속 const DeveloperPoint = function(name, age, part, programLanguage, point) { Developer.apply(this, arguments); this.point = point; } DeveloperPoint.prototype = Object.create(Developer.prototype); DeveloperPoint.prototype.constructor = DeveloperPoint; // 상속 // Class 사용 const firstDeveloperPoint = new DeveloperPoint('Lion', 22, 'Back-End', ['JavaScript', 'Node.js'], 7); const twoDeveloperPoint = new DeveloperPoint('Jane', 21, 'Front-End', ['JavaScript'], 8); ...

Code - Class

// Class // Class 생성 class Developer { constructor(name, age, part, programLanguage) { this.name = name; this.age = age; this.part = part; this.programLanguage = programLanguage; } } // Class 상속 class DeveloperPoint extends Developer { constructor(name, age, part, programLanguage, point) { super(name, age, part, programLanguage); this.point = point; } } // Class 사용 const firstDeveloperPoint = new DeveloperPoint('Lion', 22, 'Back-End', ['JavaScript', 'Node.js'], 7); const twoDeveloperPoint = new DeveloperPoint('Jane', 21, 'Front-End', ['JavaScript'], 8); ...

Class를 상속할 때 Function보다 더 쉽게 상속할 수 있다.

from http://xsop.tistory.com/39 by ccl(A) rewrite - 2021-11-06 12:27:36