자료구조 & 알고리즘

[자료구조] 선형자료구조 프로토타입 정의 및 실습

진기명기 2023. 3. 8. 12:00
🫠 선형자료구조 - 프로토타입에 대하여 아래와 같이 정리하였다.

 

 

 

🫠 프로토타입이란?

> 객체의 모태가 되는 원형

> js는 프로토타입을 이용한 복사를 통해 새로운 객체를 생성

> 정의 방법 : 속성 - 생성자, 메서드 - 프로토타입 

/* 프로토타입 */

// 객체 생성 정의
function Person(name, age, weigth, heigth){
  this.name = name
  this.age = age
  this.weigth = weigth
  this.heigth = heigth
}

// prototype을 이용한 Person 메서드 정의(1)
Person.prototype.isAdult = function(){
  return this.age > 18
}

// prototype을 이용한 Person 메서드 정의(2)
Person.prototype.isFat = function(){
  return this.weigth >= 80
}

// prototype을 이용한 Person 메서드 정의(3)
Person.prototype.isTall = function(){
  return this.heigth >= 180
}

// 객체 생성
const KIM = new Person('kim', 20, 75, 160)
const LEE = new Person('lee', 27, 80, 180)
const CHO = new Person('cho', 18, 56, 164)
const JUNG = new Person('jung', 15, 85, 181)
👉🏻 Person 생성자 속성을 정의하고, prototype을 이용하여 3가지의 메서드를 정의했다.
👉🏻 Person 생성자를 사용하여 KIM, LEE, CHO, JUNG 총 4가지의 객체를 생성하였다.

 

 

객체를 출력하면 어떻게 나올까?

console.log(KIM)
console.log(LEE)
console.log(CHO)
console.log(JUNG)

/*
Person { name: 'kim', age: 20, weigth: 75, heigth: 160 }
Person { name: 'lee', age: 27, weigth: 80, heigth: 180 }
Person { name: 'cho', age: 18, weigth: 56, heigth: 164 }
Person { name: 'jung', age: 15, weigth: 85, heigth: 181 }
*/

 

 

3가지의 메서드를 통해 각 객체에 해당하는 반환값을 받아보자

console.log(KIM.isAdult(), KIM.isFat(), KIM.isTall())
console.log(LEE.isAdult(), LEE.isFat(), LEE.isTall())
console.log(CHO.isAdult(), CHO.isFat(), CHO.isTall())
console.log(JUNG.isAdult(), JUNG.isFat(), JUNG.isTall())

/*
true false false
true true true
false false false
false true true
*/
👉🏻 각 객체에 맞는 Boolean 값이 반환된 것을 확인할 수 있다.