taenyLog
JavaScript - Prototype 본문
프로토타입은 JavaScript 객체가 서로 기능을 상속하는 매커니즘이다.
const myObject = {
city: "Madrid",
greet() {
console.log(`Greetings from ${this.city}`);
},
};
myObject.greet(); // Greetings from Madrid
city는 하나의 데이터 속성Madrid와 하나의 메서드greet()를 가진 객체이다. greet().와 같이 콘솔에 객체 이름뒤 마침표를 입력하면 콘솔이 기 객체에 사용할 수 있는 모든 속성 목록을 아래와 같이 팝업으로 표시
JavaScript의 모든 객체에는 프로토타입이라는 내장 속성이 있다.
프로토타입은 그 자체로 객체이므로 프로토타입은 자체 프로토타입을 갖게 되어 프로토타입 체인이라고 불리는 것을 만든다.
null 자체 프로토타입이 있는 프로토타입에 도달하면 체인은 종료
!주의!
프로토타입을 가르키는 객체의 속성은 prototype. 이라고 부르지않는다. 그것의 이름이 기준은 아니지만 모든 브라우저는 __proto__ 를 사용한다. 객체의 속성에 접근하는 방법은 Object.getPrototypeOf()이다.
객체의 속성에 접근하려고 할때 개체 자체에서 속성을 찾을 수 없는 경우 프로토타입에서 속성을 검색한다.
프로토타입의 프로토타입을 검색하는 식으로 속성을 찾거나 체인의 끝에 도달하면 이경우 undefined가 반환된다.
예 >
myObject.toString()
toString을 myObject에서 찾는다.
myObject에서 찾을 수 없다면 myObject의 프로토타입 객체에서 찾는다 .
거기서 찾으면 그것을 불러온다.
프로토타입 설정
JavaScript에서 객체의 프로토타입을 설정하는 다양한 방법이 있다 .
1. Object.create
이 메서드는 새로운 객체를 생성하고 새 객체의 프로퇕입으로 사용할 객체 지정
const personPrototype = {
greet() {
console.log("hello!");
},
};
const carl = Object.create(personPrototype);
carl.greet(); // hello!
personPrototype 개체는 greet() 메서드가 있는 개체를 만든다. 새로운 객체를 personPrototype 를 프로토타입으로 사용하기위해 Object.create()를 사용한다.
2.constructor
const personPrototype = {
greet() {
console.log(`hello, my name is ${this.name}!`);
},
};
function Person(name) {
this.name = name;
}
Object.assign(Person.prototype, personPrototype);
// or
// Person.prototype.greet = personPrototype.greet;
JavaScript에서 모든 함수는 prototype이라는 속성이 있다. 함수를 생성자로 호출하면 이 속성이 새로 생성된 개체의 프로토타입으로 설정(__proto__)
1. greet() 메서드를 가진 personPrototype 객체
2. person이름을 가진 Person() 생성자 함수
person함수의 프로토타입을 정의된 personPrototype에 넣는다
'Web' 카테고리의 다른 글
JavaScript 버튼 생성 (0) | 2023.06.15 |
---|---|
JavaScript 객체 복사 (0) | 2023.06.15 |
API이용하여 프로그램 검색 앱 (0) | 2023.06.14 |
서버에게 GET요청 (0) | 2023.06.14 |
FETCH (0) | 2023.06.14 |