Javascript

생성자 함수

자라나라나무나무나 2022. 5. 27. 22:08

new.target()

- 유사한 객체를 다중으로 만들 때 사용되는 함수
- 생성자 함수의 첫 글자는 대문자로 시작
- 생성자 함수로 객체 생성 시 new 연산자를 통해 객체생성
// 빵틀
function fishBread(flavor, price) {
    this.flavor = flavor;
    this.price = price;
    this.base = "flour";
};

// 붕어빵
let bread1 = new fishBread("cream", 1200);
console.log(bread1);

 


new.target() 이라는 property를 통하여 new가 붙여졌는지 안붙여졌는지 확인하는 법

function User(name) {
    console.log(new.target);
};

let result1 = User("john");
let result2 = new User("john");


재귀함수를 이용해 new가 안붙여진 생성자에게 new를 붙여준다.

function User(name) {
    if(!new.target) {
        return new User(name);
    }
    this.name = name;
};

let result1 = User("john");
console.log(result1);
let result2 = new User("john");
console.log(result2);

new가 undefind 이기 때문에 !를 붙여서 true를 만든다. 

true일 때 new 를 붙여서 자기자신을 다시 호출한다.