JavaScript ) 객체지향 문법 (constructor / prototype)

윤보라·2023년 1월 19일

자바스크립트

목록 보기
8/11

1. Constructor

: 비슷한 object를 여러 개 만들고 싶을 때 사용하면 유용함

1) 기본 구조

function Constructor1(){
	this.name = "bora"; // 여기서의 this는 새로 만들어지는 객체를 뜻하게됨 = **instance**
    this.age = 30;
}

const user1 = new Constructor1();
// Constructor1 {name: "bora", age: 30}

2) 파라미터로 매번 다른 값을 갖는 object 생성

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

const user2 = new Constructor2("ddubie", 1);
// Constructor2 {name: "ddubie", age: 1}

2. Prototype

: 위와 같은 상속의 상황에서 부모 constructor에 prototype을 설정해주면 모든 자식요소에서 꺼내 쓸 수 있음

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

Constructor2.prototype.gender = "male" // prototype 추가

const user2 = new Constructor2("ddubie", 1);
// Constructor2 {name: "ddubie", age: 1}  →→ 객체 자체가 바뀌는건 아니다

console.log(user2.gender);
// male  →→ prototype에 추가한 값을 자식요소에서 꺼낼 수 있음

* Prototype의 동작원리

우리는 어떻게 기본 내장함수를 사용 할 수 있는것일까?

const arr = [1,2,3]

arr.sort();
// 별도의 함수를 만든적이 없는데 함수를 사용할 수 있다.

실행순서)
1. arr에서 sort라는 함수를 가지고있는가? → X
2. 그 부모요소의 prototype에 sort라는 함수를 가지고있는가? → O

why? arr를 새로 만든다는건 자바스크립트의 Array라는 constructor를 통해 만들어진다는 의미

const arr = [1,2,3]

는 어떤 동작이냐면, 

const arr = new Array(1,2,3)

이렇게 자바스크립트가 갖고있는 constructor를 통해 만들어낸 array인 것!

그렇기 때문에 부모요소인 Array라는 constructor에서 prototype에 갖고있는 다양한 내장함수들을 자연스럽게 사용할 수 있는 것이다!!

* prototype의 특징

  1. 함수에만 생성됨
  2. 부모의 prototype을 확인하는 키워드 : __proto__
arr.__proto__;
  1. __proto__로 강제 부모-자식관계 등록할 수 있음
const parents = { name : "bora" };
const child = {};

child.__proto__ = parents;

console.log(child.name);
// 'bora'
  1. 콘솔창에서 prototype chain을 확인할 수 있음(__proto__항목 확인)

* Object.create(ES5)

let a = { name : "bora" }
let b = Object.create(a)
 //         ↑ b의 prototype을 a로 해주세요 라는 뜻이됨
=> b(자식)에서 a(부모)를 상속받게됨

위 상황을 콘솔로 찍어보면 어떻게나올까?

console.log(b){}
// 왜?? b를 직접적으로 정의해준적이 없기 때문에 비어있는것이 당연!

console.log(b.name)"bora"
// 왜?? 가장먼저 b에서 name을 갖고있는지 확인 후, 없으면 부모 prototype에 name이 있는지 확인해서 출력해주기때문.
profile
Front-End 개발자

0개의 댓글