관리 메뉴

공부기록용

생성자 함수 본문

💡깨달음💡/Javascript

생성자 함수

과부하가즈아 2024. 3. 27. 20:02

생성자 함수

"객체를 생성하는 역할을 하는 함수" 

 

  1. 함수의 이름의 첫 글자는 대문자로 시작한다.
    • 일반 함수와 구분하기 위함
  2. 'new'연산자를 붙여서 실행한다.
    • new 키워드를 사용하지 않으면 일반적인 함수와 동일하게 동작하여 새로운 객체를 반환하지 않는다.
  3. 생성자 함수엔 보통 return 문이 없다. 반환해야 할 것들은 모두 this에 저장되고, this는 자동으로 반환되기 때문에 반환문을 명시적으로 써 줄 필요가 없다. 만약 return 문이 있다면 아래와 같은 간단한 규칙이 적용된다.
    • 객체를 return 한다면 this 대신 객체가 반환
    • 원시형을 return 한다면 return문이 무시
    return 뒤에 객체가 오면 생성자 함수는 해당 객체를 반환해주고, 이 외의 경우는 this가 반환된다.

일반적으로 개별적인 객체 생성

let person = {
  name: "홍길동",
  age: "20",
  job: "student",
};

console.log(person);        // { name: '홍길동', age: '20', job: 'student' }
console.log(person.name);   // 홍길동
console.log(person['name']);// 홍길동
console.log(person.age);    // 20
console.log(person.name);   // student

이런 유형의 객체를 여러개 생성

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

let person1 = new Person("첳수", 25, "designer");
let person2 = new Person("영희", 28, "nurse");

console.log(person1);  // Person { name: '첳수', age: 25, job: 'designer' }
console.log(person2);  // Person { name: '영희', age: 28, job: 'nurse' }

생성자 함수 선언 기본 형식

function User(name) {
  // this = {};  (빈 객체가 암시적으로 만들어짐)

  // 새로운 프로퍼티를 this에 추가함
  this.name = name;
  this.isAdmin = false;

  // return this;  (this가 암시적으로 반환됨)
}
function 생성자함수이름(매개변수, 매개변수, 매개변수){
	// 공통적인 항목
	this.속성 = 값(공통);
	this.속성 = 값(공통);
	
    // 변경될 항목
	this.속성 = 값(매개변수);
	this.속성 = 값(매개변수);
	this.속성 = 값(매개변수);

	// 메서드
	this.메서드이름 = function(){…}
};

var 변수이름 = new 생성자함수이름(매개변수, 매개변수, 매개변수);

function Person(name, age, job, hobby) {
  this.name = name;
  this.age = age;
  this.job = job;

  // 새로운 속성 추가
  this.hobby = hobby;
}

let person1 = new Person("첳수", 25, "designer");
let person2 = new Person("영희", 28, "nurse");
let person3 = new Person("진수", 26, "student", "riding");

console.log(person1);  // Person { name: '첳수', age: 25, job: 'designer', hobby: undefined }
console.log(person2);  // Person { name: '영희', age: 28, job: 'nurse', hobby: undefined }
console.log(person3);  // Person { name: '진수', age: 26, job: 'student', hobby: 'riding' }
function Product(name, price, delivery) {
  this.name = name;
  this.price = price;
  this.delivery = delivery;

  this.info = function () {
    console.log(
      `${name}의 가격은 ${price.toLocaleString()}이고, ${delivery}인 상품`
    );
  };
}

let item1 = new Product("무드등", 23000, "로켓배송");
let item2 = new Product("사과", 15000, "새벽배송");

item1.info() // 무드등의 가격은 23,000이고, 로켓배송인 상품
item2.info() // 사과의 가격은 15,000이고, 새벽배송인 상품

prototype

생성자 함수로 생성된 객체들이 속성과 메서드를 공유하기 위해서 사용하는 객체로 메모리 효율을 줄이기 위해 공통된 부분을 prototype키워드로 빼서 작성한다.

function Product(name, price, delivery) {
  this.name = name;
  this.price = price;
  this.delivery = delivery;
}

Product.prototype.company = "coupang";
Product.prototype.deliveryPrice = "무료배송";

Product.prototype.result = function() {
  console.log(
    `${this.company}의 ${this.deliveryPrice}인 ${this.name}의 가격은 ${this.price.toLocaleString()}이고, ${this.delivery}인 상품`
  );
};

let item1 = new Product("무드등", 23000, "로켓배송");
let item2 = new Product("사과", 15000, "새벽배송");

item1.result();  // coupang의 무료배송인 무드등의 가격은 23,000이고, 로켓배송인 상품
item2.result();  // coupang의 무료배송인 사과의 가격은 15,000이고, 새벽배송인 상품

 

 

 

🔗참고🔗

https://ko.javascript.info/constructor-new

https://ko.javascript.info/function-prototype

Comments