[JS] 생성자 함수 (코딩앙마 자바스크립트 중급)

김다빈·2023년 8월 6일
0

자바스크립트

목록 보기
28/36
post-thumbnail

🚩 생성자 함수

일반 함수 만들듯이 함수명과 매개변수 넣어서 만들면 된다.

  • 이때 함수명은 무조건 대문자로 시작한다.
  • new 키워드를 붙여 실행한다. (new 붙이지 않으면 일반 함수 실행과 같음)
function User(name, age) {
  //this = {}; (빈 객체가 암시적으로 만들어짐)
  this.name = name;
  this.age = age;
  this.sayName = function () {
    console.log(this.name);
  }
  // return this; (this가 암시적으로 반환됨)
}

const user1 = new User('Mike', 30);

console.log(user1) //출력 결과 : user1 객체 자체
user1.sayName(); //Mike

✅ 예제

function Item(title, price) {
  this.title = title;
  this.price = price;
  this.showPrice = function() {
    console.log(`${title}의 가격은 ${price}원 입니다.`)
  }
}
>
const item1 = new Item('인형', 3000);
const item2 = new Item('가방', 4000);
const item3 = new Item('지갑', 9000);
>
item1.showPrice(); //인형의 가격은 3000원 입니다.
item2.showPrice(); //가방의 가격은 4000원 입니다.
item3.showPrice(); //지갑의 가격은 9000원 입니다.
profile
Hello, World

0개의 댓글

관련 채용 정보