특정 함수를 선언할 때에 new 를 붙여 선언하면 새롭게 만들어지는 객체형태로 선언되며 내부 값들이 키값구조를 가진 오브젝트 형태 자체가 된다. 생성자 함수라고 부르며 this 선언을 통해 생성될 데이터를 선언하며 매우 중요하다. new Date 혹은 new FormData 등등의 다른 기능을 통해서도 알 것이다. 함수 규칙을 통해 매개변수로 들어간 데이터에 기반한 변형값을 만드는데 사용된다. 관례로 생성자 함수는 첫글자를 대문자로 한다. 예시,
function Example() {
this.value = 42;
return "Not an object";
}
// 이 함수는 new 생성자가 금지된다 !!!
const Example = () => {
this.value = 42;
return "Not an object";
}
// 함수 호출
let result1 = Example();
console.log(result1); // "Not an object"
console.log(typeof result1); // "string"
// 생성자 호출
let result2 = new Example();
console.log(result2); // Example { value: 42 }
console.log(typeof result2); // "object"
중요한 점은 화살표 함수로 만들어진 함수의 this는 자신의
this를 가지지 않고 따라서 생성자로 절대 사용해선 안된다. (타입에러 발생)
함수 내부에 또 함수를 넣어 나중에 데이터화 되었을 때에 실행되는 내부함수 구조로 만들 수 도 있다. 물론 함수도
this.함수구조를 가진다. canvas 애니메이션 객체 항목 참조,
cunstructor 라는 생성자 함수의 클래식한 방법도 있는데,
class Person {
constructor(name, age) {
this.name = name; // this는 새로 생성된 객체를 가리킴
this.age = age;
}
greet() {
console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
}
}
const alice = new Person('Alice', 25);
alice.greet(); // "Hello, my name is Alice and I am 25 years old."
이와같이 생성자를 사용하는 방법으로 자세한 사항은 연구중.
생성자 함수 내부에 함수를 prototype 으로 선언하는 경우가 있다.
function Person(name, age) {
this.name = name;
this.age = age;
}
Person.prototype.greet = function() {
console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
};
const alice = new Person('Alice', 25);
const bob = new Person('Bob', 30);
alice.greet(); // "Hello, my name is Alice and I am 25 years old."
bob.greet(); // "Hello, my name is Bob and I am 30 years old."
모든 JavaScript 함수에는
prototype이라는 속성이 있공, 이prototype속성은 객체로, 해당 함수로 생성된 객체 인스턴스가 상속받을 수 있는 속성과 메서드를 정의할 수 있음. 이 객체 안에 정의된 메서드나 속성은 그 함수로 생성된 모든 인스턴스에서 공유됨. 메모리 관리에서 유리하다고 알려져 있으나 자세한 사항은 연구중.