생성자 함수

dev_sang·2022년 6월 29일
0

JavaScript

목록 보기
9/11



생성자 함수란?

  • new 연산자와 함께 호출하여 객체를 생성하는 함수입니다.
  • 생성자 함수에 의해 만들어진 객체를 인스턴스(instance)라고 합니다.
const instance = new Obj();

생성자 함수의 종류

  • Object 생성자 함수
  • String, Number, Boolean, Function, Array, Date, RegExp, Promise 등의 빌트인 생성자 함수들

생성자 함수와 객체 리터럴의 차이

  • 객체 리터럴은 여러개의 객체를 생성하지 못하고 한개의 객체만을 생성합니다.
  • 생성자 함수는 여러개의 객체(인스턴스)를 만들 수 있습니다.
  • 생성자 함수를 통해 프로퍼티 구조가 동일한 여러개의 객체를 템플릿처럼 간편하게 만들 수 있습니다.
function Circle(radius){ 	// 생성자 함수
  this.radius = radius;  	// this는 생성자 함수가 생성할 인스턴스를 가리킴
  this.getDiameter = function () {
    return 2 * this.radius;
  };
};

// Instance 생성
const circle1 = new Circle(5); 		// 반지름이 5인 Circle 객체를 생성
const circle2 = new Circle(10); 	// 반지름이 10인 Circle 객체를 생성

console.log(circle1.getDiameter()); // 10
console.log(circle2.getDiameter()); // 20


객체(인스턴스)를 만드는 과정

  1. 생성자 함수 선언
  2. 인스턴스 생성
  3. 인스턴스 초기화
  4. 인스턴스 반환

function Circle(radius) {			// 1. 생성자 함수 선언
  this.radius = radius;				// 3. 인스턴스 초기화
  this.getDiameter = function () {
  return 2 * this.radius;
  };
  
// 4. 생성자 함수를 호출할 때 넣은 인수를 인스턴스 생성 시에 this 바인딩을 통해 프로퍼티에 할당한 뒤, 인스턴스를 반환한다

const circle1 = new Circle(5); 		// 2. 인스턴스 생성 (반지름이 5인 Circle 객체를 생성)

profile
There is no reason for not trying.

0개의 댓글