JavaScript
[JavaScript] 생성자 함수
김도유
2022. 9. 15. 13:20
생성자 함수는 붕어빵 틀이라고 생각하면 된다. 필요한 재료를 넣어주고 찍어내는 것이다.
보통 첫글자는 대문자로 생성한다.
function User(name, age) { // 첫 글자는 대문자
this.name = name;
this.age = age;
}
let user1 = new User('Mike', 30); //new 연산자 사용해서 호출
let user2 = new User('Jane', 20);
let user3 = new User('Tom', 17);
필요한 재료는 이름과 나이다.
User라는 함수를 만들고, 이름(name)과 나이(age)를 인자로 받아서 this에 넣어준다.
new 연산자를 사용해서 함수를 호출한다.
각각 다른 변수명으로 3번 연달아 호출한다. 객체 3개를 생성했다.
new 함수명();
함수를 실행하면 아래와 같이 동작한다.
function User(name, age) { // 첫 글자는 대문자
this = {}
this.name = name;
this.age = age;
return this;
}
1. 빈 객체를 만들고 this에 할당한다.
2. this에 property(프로퍼티)들을 추가한다.
3. this를 반환한다.
다음은, 메소드를 추가해보겠다.
function User(name, age) { // 첫 글자는 대문자
this.name = name;
this.age = age;
this.sayName = function(){
console.log(this.name);
}
}
let user5 = new User('Han', 40);
user5.sayName(); // 'Han'
this로 할당된 객체에 sayName메소드를 추가하고 user5를 생성했다.
user5의 sayName메소드를 호출하면 이름을 출력한다.
//생성자 함수 : 상품 객체를 생성해보자.
function Item(title, price){
// this = {};
this.title = title;
this.price = price;
this.showPrice = function(){
console.log('가격은 ${price}원 입니다.');
};
//return this;
}
const item1 = new Item("인형", 3000); //생성자 함수는 new를 붙여야함 new를 붙이지 않으면 함수가 실행
const item2 = new Item("가방", 4000);
const item3 = new Item("지갑", 5000);
console.log(item1, item2, item3);
item3.showPrice(); //메소드 호출
Item {title : "인형", price: 3000, showPrice: f} //console.log(item1, item2, item3);
Item {title : "가방", price: 4000, showPrice: f}
Item {title : "지갑", price: 5000, showPrice: f}
가격은 5000원 입니다. // item3.showPrice();
참고 및 출처 : 유투브 코딩앙마 https://youtu.be/4_WLS9Lj6n4