push()
메서드를 사용한다.const arr = [1, 2, 3, 4];
arr.push(5); // 5 (배열의 새로운 길이를 반환)
console.log(arr); // [1, 2, 3, 4, 5]
arr
에 이런 메서드를 추가해준 적이 없는데 어떻게 사용이 가능한걸까?new 생성자함수명()
을 사용해서 새로운 객체를 생성하는 것이다.const arr = new Array(1, 2, 3, 4);
arr.push(5); // 5 (배열의 새로운 길이를 반환)
console.log(arr); // [1, 2, 3, 4, 5]
arr
라는 변수를 배열 리터럴([]
)로 생성했지만new Array()
로 새로운 Array
객체를 생성한 것이다. (참고링크)push()
메서드는 Array
의 prototype
프로퍼티에 속성으로써 정의되어 있다.Array.prototype
를 검색해보자!push()
메서드 외에도 다양한 내장 메서드들이 존재하는 것을 알 수 있다. 👀new
키워드로 생성자 함수를 사용해 객체를 만들면 생성자 함수의 prototype
프로퍼티와 새롭게 만들어진 객체 인스턴스 사이에는 일종의 연결고리가 생긴다.Array
라는 부모 객체(프로토타입)가 있고, 자식인 arr
가Array
에게 메서드를 상속받아 사용할 수 있게 된 것이다.__proto__
프로퍼티(속성)__proto__
프로퍼티에 접근하면 내부적으로 Object.getPrototypeOf
가 호출되어 프로토타입 객체를 반환한다.arr
객체는 __proto__
프로퍼티로 자신의 부모 객체인 Array.prototype
을 가리키고 있다.OOP 패턴으로 구현한 Human 예시
class Human {
constructor(name, age) {
this.name = name;
this.age = age;
}
sleep() {
console.log(`${this.name}은 잠에 들었습니다`);
}
}
// 생성자 함수를 이용해 객체를 생성한다. new 키워드를 이용한다.
let kimcoding = new Human('김코딩', 30);
Human
클래스의 생성자(constructor) 함수는 Human
이다.
Human.prototype.constructor === Human; // ture 클래스
Human
클래스의 prototype
은 Human
클래스의 인스턴스인 kimcoding
의 __proto__
이다.
Human.prototype === kimcoding.__proto__; // ture 프로토타입
Human
클래스의 sleep
메서드는 prototype
에 있으며, Human
클래스의 인스턴스인 kimcoding
에서 kimcoding.sleep
으로 사용할 수 있다.
Human.prototype.sleep === kimcoding.sleep; // ture 인스턴스
- 클래스
Human
과 인스턴스kimcoding
,prototype(프로토타입)
의 관계