자바스크립트 생성자 함수

joyoung·2024년 1월 7일

생성자 함수

function Profile (name, age) {
    
  this.name = name;
  this.age = age;
  this.introduce = function () {
    return `안녕하세요, ${this.age}세 ${this.name}입니다!`;
  }
}

const people = new Profile('짱구' ,5)

console.log(people)

instrument.ts:113 Profile {name: '짱구', age: 5, introduce: ƒ}

생성자 함수명은 일반적으로 대문자로 시작 - 파스칼 케이스

생성자 함수로 만들어진 객체를 인스턴스 instance 라 부름

this.name 과 같이 생성될 인스턴스의 프로퍼티들 정의

생성자 함수는 new 연산자와 함께 사용

암묵적으로 this 반환
return 값이 없어도 this 객체 반환

생성자 함수에서는 메서드 정의 불가 - 객체 리터럴과 클래스에서는 가능

profile
꾸준히

0개의 댓글