객체를 여러개를 만들어야 할 때 사용한다.
//객체 리터럴
let user= {
name:'Joon',
age : 30,
showName:function(){
console.log(this.name);
}
}
//생성자함수
function User(name,age){
this.name=name;
this.age=age;
this.showName=function(){
console.log(this.name);
}
}
let user1 = new User('jery',32);
let user2 = new User('kim',20);
new를 사용하여 생성자함수로 객체를 만드는 과정이다. 여기서 생성자함수에서 생략되는 부분이 있는데 new키워드를 사용하면 자동으로 프로그램이 실행될 때 생성해준다.
function User(name,age){ // 첫글자를 대문자
this = {} // 생략
this.name=name;
this.age = age;
return this; // 생략
}