다음과 같이 여러 번 비슷한 코드가 반복되는 경우 생성자 함수를 사용할 수 있다. 생성자 함수란 new키워드를 사용하는 함수이다.
const flyda = {
firstName: 'Flyda',
lastName: 'Yang',
getFullName : function () {
return `${this.firstName} ${this.lastName}`
}
}
console.log(flyda.getFullName())
const amy = {
firstName: 'Amy',
lastName: 'Hwang',
getFullName : function () {
return `${this.firstName} ${this.lastName}`
}
}
console.log(amy.getFullName())
const neo = {
firstName: 'Neo',
lastName: 'Lee',
getFullName : function () {
return `${this.firstName} ${this.lastName}`
}
}
console.log(neo.getFullName())
생성자 함수를 사용해서 작성한 코드는 다음과 같다.
function User(first, last) {
this.firstName = first
this.lastName = last
}
User.prototype.getFullName = function () {
return `${this.firstName} ${this.lastName}`
}
const flyda = new User('Flyda' , 'Yang')
const amy = new User('Amy', 'hwang')
const neo = new User ('Neo' , 'Lee')
console.log(flyda.getFullName())
console.log(amy.getFullName())
console.log(neo.getFullName())
user의 이름과 성은 계속 다르게 입력받을 수 있기 때문에 통일해서 관리하기에 어려움이 있다.
하지만 user이라는 함수에 숨어져 있는 prototype속성에 getFullName을 할당해주면 flyda, amy 등 다양한 객체를 만들어도 이 함수는 메모리에 한 번만 만들어지게 된다!
밑에서 console.log에서 출력하는 내용은 getFullName을 참조하는 개념이다!!
요약!
생성자 함수가 new라는 키워드와 함께 사용되어야 하는 함수이기 때문에 일반 함수와 구분하기 위해서 함수의 첫 시작을 대문자(파스칼 케이스)로 해준다!
모던 자바스크립트 해당 부분 주소 : https://ko.javascript.info/constructor-new
'핀테크 서비스 프론트엔드 개발자 취업 완성 2기 > JS' 카테고리의 다른 글
[JS] 상속(확장) (0) | 2022.04.15 |
---|---|
[JS] ES6 Classes (0) | 2022.04.15 |
[JS] this (0) | 2022.04.15 |
[JS] 데이터 타입 확인 함수 (0) | 2022.04.14 |
[JS] Uncaught typeError: Failed to execute 'scrollTo' on 'window': the provided value is not of type 'scrollToOptions'. 해결방법 (0) | 2022.04.13 |
댓글