JavaScript의 new 키워드 검사

IT공부중·2020년 7월 12일
6

JavsScript

목록 보기
1/22
post-thumbnail

자바스크립트에서 함수 또는 class에 new 키워드를 통해 호출하면 생성자로 사용할 수 있다.

function

function 생성자로 객체 인스턴스를 사용하려면 이런 식으로 코드를 작성하면 된다.

function Student(name, age) {
  this.name = name;
  this.age = age;
}

const student = new Student('문건우', 26);
console.log(student);
console.log(student.name, student.age);

보통 함수 생성자 함수의 변수명은 PascalCase로 작성한다.
이렇게 실행을 하게 되면

이런 결과가 나타난다.

하지만 function 생성자는 new 키워드 없이 실행을 할 경우에도 에러가 발생하지 않는다.
그래서 this가 전역개체가 되고 반환 값이 없기 때문에 undefined가 저장될 것이다.

function Student(name, age) {
  this.name = name;
  this.age = age;
}

const student = Student('문건우', 26);
console.log(student);
console.log(student.name, student.age);

따라서 이렇게 실행하게 되면 student에는 undefined가 출력될 것이고,
undefined의 name, age는 없기 때문에 다음과 같은 에러가 나타나게 된다.

그러면 new 키워드를 사용해서 선언했는지는 어떻게 알 수 있을까?
아래의 코드를 보자. new.targetinstanceof를 사용하였다.

function Student(name, age) {
  console.log(new.target);
  console.log(this instanceof Student);
  this.name = name;
  this.age = age;
}

const student = new Student('문건우', 26);
console.log(student);
console.log(student.name, student.age);

만약 new를 사용하지 않고 실행을 한다면

이렇게 출력 되고 밑에는 에러가 나올 것이다.
new.target은 없어서 undefined가 나올 것이고, new 키워드가 없을 때의 this는 전역객체이기 때문에, Student의 instance가 아니라서 false가 나올 것이다.

즉, new를 썼는지 안 썼는지를 확인 하는 방법으로 new.target을 확인 하는 방법과, this가 Student의 instance 인지를 확인하는 방법(instanceof)이 있다.

function Student(name, age) {
  if (!new.target) {
    throw new Error('new 키워드를 사용해주세요!');
  }
  this.name = name;
  this.age = age;
}

try {
  const student = Student('문건우', 26);
  console.log(student);
  console.log(student.name, student.age);
} catch (e) {
  console.error(e);
}
console.log('1234');

그래서 이렇게 사용한다면 new 키워드를 사용하지 않았을 경우에 new 키워드를 사용해주세요.라는 error을 던지고 밑의 '1234' 까지 출력이 되는 것을 볼 수가 있다.

class

객체를 생성하는 ES6에서 나온 class의 경우에는 new 키워드를 붙이지 않고 객체 인스턴스를 생성할 경우 Error가 나게 된다.

class App {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }
}

const app = App('문건우', 26);

console.log(app.name);
console.log(app.age);

원래 new를 붙이고 실행을 하게 되면 다음과 같이 나타난다.

즉, class로 작성할 경우에는 new를 사용해 생성했는지 아닌지의 검사를 자동으로 해주는 것이다.

profile
3년차 프론트엔드 개발자 문건우입니다.

0개의 댓글