function Student(name, grade, age){
this.name = name;
this.grade = grade;
this.age = age;
}
var student = Student("Woody Choi", 1, 20);
alert(student.name);
alert(student.grade);
alert(student.age);
new 생성자 없이 Student를 선언을 하면 에러가 발생하게 된다. 왜냐하면, this를 window로 인식을 하게 되기 때문이다. 이를 해결하기 위해서 다음과 같은 처리를 할 수 있다.
Self-scope 생성자는 먼저 this가 Student type인지를 확인하고, 그렇지 않으면 new 를 이용하여 객체를 생성한다.
function Student(name, grade, age){
if (this instanceof Student){
this.name = name;
this.grade = grade;
this.job = job;
}
else{
return new Student(name, grade, age);
}
}
var student = Student("Woody", 1, 34);
alert(student.name);
alert(student.grade);
alert(student.age);