솔미는 성장중

[JS] prototype + 배열 만드는 방법 본문

JavaScript

[JS] prototype + 배열 만드는 방법

solming 2023. 7. 19. 00:06
728x90
colors.test()

배열 만드는 방법

1. 리터럴 방식으로 배열 만들기

const colors = ['Red', 'Green', 'Yellow', 'Blue']

 

2. 생성자 함수 형식으로 배열 만들기 (new사용)

const colors = new Array('Red', 'Green', 'Yellow', 'Blue')

console.log(colors)
//(4) ['Red', 'Green', 'Yellow', 'Blue']
//0: "Red"
//1: "Green"
//2: "Yellow"
//3: "Blue"
console.log(colors.includes('Green')) //true
console.log(colors.length) //4

여기서 length, includes를  prototype 속성, prototype 메소드 라고 한다.


 

 

Prototype 이란?

new키워드를 통해 만든 생성자 함수에서 반환된 결과인 인스턴스에서 쓸 수 있는

별도의 속성이나 메소드를 등록하는 객체


prototype 메소드 만들 때 주의할 점

일반함수로 만들어주어야 한다.

화살표 함수를 쓰면 this가 가리키는 게 의도한 바와 달라진다.

 


간단 예시

Array.prototype.test = function () {
  console.log(this)
}

임의로 만든 함수를 할당한 것.

인위적으로 만든 메소드는 기본적으로 function 키워드를 사용하는 일반함수를 써야한다.

colors.test()

이후 호출을 해보면 사용가능한 것을 확인할 수 있다.

이는 colors라는 배열에서만 쓸 수 있는 것이 아니라 다른 배열에서도 배열명.test 형태로 사용 가능하다.

 


난이도 업 예시

const test1 = {
  firstName: 'Chulsu',
  lastName: 'Kim',
  getFullName() {
    return `${this.firstName} ${this.lastName}`
  }
}
const test2 = {
  firstName: 'Younghee',
  lastName: 'Park'
}
console.log(test1.getFullName()) //Chulsu Kim
console.log(test2.getFullName.call(test2)) //Younghee Park

test2라는 객체 데이터에서 getFullName을 사용하려면 test1의 getFullName을 빌려서 사용했어야했다.

위 내용의 코드를 prototype을 사용한 방식으로 수정해 볼 것이다.

 

 

1단계) this 와 생성자 함수 사용해보기

 function User(first, last){
   this.firstName = first
   this.lastName = last
 }

 const test1 = new User('Chulsu','Kim')
 const test2 = new User('Younghee','Park')

 console.log(test1) //User {firstName: 'Chulsu', lastName: 'Kim'}
 console.log(test2) //User {firstName: 'Younghee', lastName: 'Park'}

User라는 함수를 만드는 방법을 통해 객체 형태의 데이터를 만들어냈다. 

+ 주의할 점 ) 함수의 첫번째 글자는 대문자여야 한다.

 

2단계) Prototype 사용해보기

prototype으로 getFullName이란 메소드를 등록했기 때문에 더이상 빌려쓰지 않아도 된다.

내장된 상태이기 때문에 가져다가 쓰기만 하면 된다.

 function User(first, last){
   this.firstName = first
   this.lastName = last
 }
 //추가
 User.prototype.getFullName = function () {
  return `${this.firstName} ${this.lastName}`
 }

 const test1 = new User('Chulsu','Kim')
 const test2 = new User('Younghee','Park')

 console.log(test1) //User {firstName: 'Chulsu', lastName: 'Kim'}
 console.log(test2) //User {firstName: 'Younghee', lastName: 'Park'}
 //추가
 console.log(test1.getFullName()) //Chulsu Kim
 console.log(test2.getFullName()) //Younghee Park

 

 

 

 

 

 

 

 

참고 문헌

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array

 

Array - JavaScript | MDN

The Array object, as with arrays in other programming languages, enables storing a collection of multiple items under a single variable name, and has members for performing common array operations.

developer.mozilla.org

 

728x90

'JavaScript' 카테고리의 다른 글

[JS] 불변성  (0) 2023.07.31
[JS] DOM  (0) 2023.07.31
[JS] fetch()  (0) 2023.07.31
[JS] 동기/비동기 (콜백 패턴, promise, Async & Await, Resolve, Reject, 에러 핸들링, 반복문에서의 비동기)  (0) 2023.07.31
[JS] 모듈  (0) 2023.07.23