생성자

Geonil Jang·2021년 7월 27일
0
post-thumbnail

생성자란?

new 연산자가 붙은 함수를 의미하며 인스턴스를 만들 수 있습니다.

  • new Object();
  • new Array();
  • etc..
function My(){
}

const myObj = new My();
console.log(myObj instanceof My);
console.log(myObj.constructor === My);

생성자를 만드는 이유?

생성자의 중요한 기능은 바로 동일한 프로퍼티, 메서드를 가진 객체를 쉽게 만들어 낼 수 있다.

function Person(name){
	this.name = name;
  	this.say = function(){
    	console.log(this.name+", hello");
    }
}

const me = new Person("me");
const you = new Person("you");

me.say(); "me, hello"
you.say(); "you, hello"

new 연산자의 기능!

new 연산자가 붙으면 함수의 this는 인스턴스를 참조하게 됩니다.
new 연산자가 자동으로 인스턴스를 반환하기 때문에 함수안에 return 연산자도 필요 없어지게 됩니다.

정리

  • 생성자란 앞에 new 키워드가 붙은 함수를 의미합니다.
  • 생성자의 중요 기능은 바로 동일한 프로퍼티와 메소드를 가진 객체를 쉽게 대량생산하는데 있다.
  • 생성자 함수의 new 연산자는 인스턴스를 참조
profile
takeaways

0개의 댓글