종우의 컴퓨터 공간
★Protytypes Explained(프로토타입 기본 개념) 본문
★Protytypes Explained(프로토타입 기본 개념)
종우공간 2021. 8. 7. 10:39프로토타입 이란?
- 자바스크립트는 프로토타입 기반 언어이다.
- 자바스크립트에서 기본 데이터 타입(string, number, boolean, null, undefined)을 제외한 모든 것은 객체이다.
- 객체가 만들어지기 위해서는 자신을 만드는데 사용된 원형인 프로토타입 객체를 이용하여 객체를 만든다.
- 원형이라는 뜻으로 프로토타입 객체와 프로토타입 링크로 나눌 수 있다.
- protytype 속성은 함수만 가지고 있던 것과 달리 [[Protytype]] 속성은 모든 객체가 빠짐없이 가지고 있는 속성이다. 그 말은 함수로 통해 만들어진 객체만 프로토타입 객체가 존재하는 것이고 함수가 아닌 걸로 만든 객체는 프로토타입 객체가 존재하지 않는다. 다만 new를 통해서 기존에 존재하던 함수로 인해 복사한 객채의 경우 그 함수와 같은 프로토타입의 객체를 갖는다.(프로토타입 객체안에 있는 속성도 사용 가능하다.)
프로토타입 객체란?
- 함수를 정의하면 다른 곳에 생성되는 프로토타입 객체는 자신이 다른 객체의 원형이 되는 객체이다.
- 모든 객체는 프로토타입 객체에 접근할 수 있다.
- 프로토타입 객체도 동적으로 런타임에 멤버를 추가할 수 있다.
- 같은 원형을 복사로 생성된 모든 객체는 추가된 멤버를 사용할 수 있다.
함수와 객채의 내부 구조
- 모든 함수는 생성 시 prototype 속성을 가진다. 이 속성은 다른 곳에 생성된 함수이름의 프로토타입 객체를 참조한다.
- 프로토타입 객체는 constructor 속성을 가진다. 이 속성은 자신(프로토타입 객체)을 생성한 함수를 참조한다.
- Person 함수의 Prototype 속성이 참조하는 프로토타입 객체는 new라는 연산자와 Person 함수를 통해 생성된 모든 객체의 원형이 되는 객체이다. 그 말은 Person 함수를 통해 생성된 모든 객체(new)는 프로토타입 객체를 참조할 것이다.
예제
//Object.prototype
function Person(firstName, lastName, dob) {
this.firstName = firstName;
this.lastName = lastName;
this.birthday = new Date(dob);
}
// Calculate age; put in prototype because of reducing duplication
Person.prototype.calculateAge = function() {
const diff = Date.now() - this.birthday.getTime();
const ageDate = new Date(diff);
return Math.abs(ageDate.getUTCFullYear() - 1970);
}
// Get full name; put in prototype because of reducing duplication
Person.prototype.getFullName = function() {
return `${this.firstName} ${this.lastName}`;
}
// Gets Married; changing the value of prototype
Person.prototype.getsMarried = function(newLastName) {
this.lastName = newLastName;
}
const john = new Person('John', 'Doe', '8-12-1990');
const mary = new Person('Mary', 'Johnson', 'March 20 1978');
console.log(mary);
console.log(mary.calculateAge());
console.log(mary.getFullName());
mary.getsMarried('Smith');
console.log(mary.getFullName());
// properties of Object Prototype
console.log(mary.hasOwnProperty('firstName')); // yields true
console.log(mary.hasOwnProperty('getFullName')); // yields false
참조: https://medium.com/@bluesh55/javascript-prototype-%EC%9D%B4%ED%95%B4%ED%95%98%EA%B8%B0-f8e67c286b67
[Javascript ] 프로토타입 이해하기
자바스크립트는 프로토타입 기반 언어라고 불립니다. 자바스크립트 개발을 하면 빠질 수 없는 것이 프로토타입인데요. 프로토타입이 거의 자바스크립트 그 자체이기때문에 이해하는 것이 어렵
medium.com
참조: https://www.nextree.co.kr/p7323/
JavaScript : 프로토타입(prototype) 이해
JavaScript는 클래스라는 개념이 없습니다. 그래서 기존의 객체를 복사하여(cloning) 새로운 객체를 생성하는 프로토타입 기반의 언어입니다. 프로토타입 기반 언어는 객체 원형인 프로토타입을 이
www.nextree.co.kr
'자바 스크립트 (JavaScript) > Object Oriented JavaScript - ES5&ES2015' 카테고리의 다른 글
[ES6] Classes (0) | 2021.08.08 |
---|---|
Using Object.create() (0) | 2021.08.08 |
Prototypes Inheritance (0) | 2021.08.07 |
Built in Constructors (0) | 2021.08.07 |
[ES5] Constructors & the 'this' Keyword (0) | 2021.08.07 |