2. 생성자 함수

조뮁·2022년 7월 10일
0

JS중급

목록 보기
2/18
post-thumbnail

객체 리터럴

  • let a = 'abcd'에서 변수에 할당하는 변하지 않는 값, 데이터
  • 상수 / 변수 / 변수리터럴
    • 상수 : 변하지 않는 값
    • 변수 리터럴 : 변수에 넣는 변하지 않는 데이터
    • 변수 : 값(변수 리터럴)을 담을 수 있는 메모리 공간

-- 예시 --
b = 5
'b' 자체 (b의 메모리 위치) = 상수
5 = 객체 리터럴
b 는 계속 다른 수를 받을 수 있기 때문에 변수

-- 예시 --
let user = {
name : 'Mike',
age : 30,
}

  • 오른쪽 { ... } 부분 = 객체리터럴

생성자 함수

  • 비슷한 객체를 여러 개 만들 때 사용
  • 첫 글자는 대문자로 작성
  • new 연산자로 함수 호출
function User(name, age){
  // 1. 빈 객체를 만들고 this에 할당
  //this = {}
  
  // 2. this에 프로퍼티 추가
  this.name = name;
  this.age = age;
  
  // 3. this 반환
  return this;
}

let user1 = new User('Mike', 20);
let user2 = new User('Jane', 30);
let user3 = new User('Geon', 40);
let user4 = new User('Kasy', 50);

console.log(user1, user2, user3, user4);

new 함수명(); 실행 시 로직
1. 빈 객체를 만들고 this에 할당
2. this에 프로퍼티 추가
3. this 반환

생성자함수에 메소드 추가

function User(name, age){
  this.name = name;
  this.age = age;
  this.sayName = function(){
    console.log(this.name);
  }
}

let user5 = new User('달봉', 10);

user5.sayName();  // '달봉'

상품 객체 생성

function Item(title, price){
  // this = {};
  this.title = title;
  this.price = price;
  this.showPrice = function(){
    console.log(`가격은 ${this.price}원 입니다.`);
  }
  // return this;
}
  
let item1 = new Item('인형', 3000);
let item2 = new Item('가방', 4000);
let item3 = new Item('지갑', 5000);

console.log(item1, item2, item3);
item1.showPrice();

/*
{
  "title": "인형",
  "price": 3000,
  "showPrice": "function () {\n    console.log(`가격은 ${this.price}원 입니다.`);\n  }"
}
{
  "title": "가방",
  "price": 4000,
  "showPrice": "function () {\n    console.log(`가격은 ${this.price}원 입니다.`);\n  }"
}
{
  "title": "지갑",
  "price": 10000,
  "showPrice": "function () {\n    console.log(`가격은 ${this.price}원 입니다.`);\n  }"
}
"가격은 10000원 입니다."
*/

주의
이 때, this.showPrice() 에서 ${this.price}가 아니라 ${price}를 출력했다면???

function Item(title, price){
  // this = {};
  this.title = title;
  this.price = price;
  this.showPrice = function(){
    console.log(`가격은 ${price}원 입니다.`);
  }
  // return this;
}
  
let item1 = new Item('인형', 3000);
let item2 = new Item('가방', 4000);
let item3 = new Item('지갑', 5000);

console.log(item1, item2, item3);

item3.price = 10000;
item1.showPrice();
// "가격은 5000원 입니다."
  • 중간에 item3.price 값이 변했지만, ${this.price}를 출력하는 것이 아니기 때문에 변경된 값이 반영되지 않음.

  • ${price}는 매개변후로써, 처음 받은 값을 저장하고 있을 뿐이기 때문에 변경된 값을 출력하지 못함.

  • 만약, 생성자 함수 앞에 new를 붙여주지 않는다면 그냥 함수가 실행될 뿐임. (this에 빈 객체 할당, return없음) -> undefined 출력

0개의 댓글