모던 자바스크립트 Deep Dive를 참고하여 학습,작성하였습니다.
1.프로토타입(Prototype)
프로토타입 기반 객체지향 프로그래밍 언어인 자바스크립트는 클래스 없이도 객체를 생성할수있다.
모든 객체는 자신의 부모 역할을 담당하는 객체와 연결되어있고 부모객체의 프로퍼티, 메소드를 상속받아 사용할수있다.
이때 이런 부모객체를 프로토타입 객체라고 부른다.
student 객체는 hasOwnProperty 메소드가 없지만 프로토타입 객체에게 받았기에 사용할수있다.
function student(name,age){
this.name=name;
this.age=age;
}
document.write(student.hasOwnProperty('name'))
2.[[Prototype]]
자바스크립트의 모든 객체는 [[Prototype]]이라는 인터널 슬롯(객체가 내부적으로 사용하는, 외부에서 직접 접근할 수 없는 속성)을 가진다.
객체가 다른 객체로부터 속성이나 메서드를 상속받을 수 있도록 하는 메커니즘이다.
__proto__ 으로 프로토타입객체에 접근할수있다.
아래 studnet, student2는 모두 함수이다.
1.두함수의 __proto__는 Function.prototype이다.
2.Function또한 함수 이므로 Function의 __proto__ 또한 Function.prototype이다.
3.Function.prototype의 __proto__는 Object.prototype이다.
4.Object.prototype의 __proto__는 null이다.
function student(name,age){
this.name=name;
this.age=age;
}
function student2(name,age){
this.name=name;
this.age=age;
}
document.write(student.hasOwnProperty('name')+"<br><br><br>")
document.write((student.__proto__ == student2.__proto__)+"<br>")
document.write((student.__proto__==Function.prototype)+"<br>")
document.write((Function.prototype.__proto__==Object.prototype)+"<br>")
document.write((Function.prototype==Function.__proto__)+"<br>")
document.write((Object.prototype.__proto__)+"<br>")
3.constructor 프로퍼티
프로토타입 객체는 객체의 입장에서 자신을 생성한 객체를 가르키는 constructor 프로퍼티를 가진다.
1. Human 생성자함수로 생성된 객체를 생성한 객체는 Human() 생성자함수이다.
2. me객체를 생성한 객체는 Human() 생성자함수다.
3. Human함수를 생성한 객체는 Functon()생성자 함수다.
function Human(){}
var me=new Human();
document.write((Human.prototype.constructor==Human)+"<br>")
document.write((me.constructor==Human)+"<br>")
document.write((Human.constructor==Function)+"<br>")
4.Prototype chain
특정 객체의 프로퍼티나 메소드에 접근할때 만약 없다면 부모역할을하는 프로토타입 객체를 차례대로 검색한다.
🎈참고자료
https://poiemaweb.com/js-prototype
반응형
'FrontEnd > JavaScript' 카테고리의 다른 글
[JavaScript] 스코프(Scope) (0) | 2024.06.04 |
---|---|
[JavaScript] 타입체크 (0) | 2024.06.03 |
[JavaScript] 함수 객체의 프로퍼티 ,형태 (0) | 2024.06.03 |