일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
- 히든 스토리
- try-with-resources
- 아웃풋법칙
- colllection
- apache kafka
- 부자의그릇
- try width resources
- sentry
- 참조 계수
- 이펙티브 자바
- 레퍼런스 복사
- node
- 과제의 분리
- CSS
- 월칙
- 비메모리 자원
- 모두가 기다리는 사람
- 칭기즈칸의 위대한 장군 수부타이
- 공헌감
- ESG
- kubernetes
- java
- docker
- 뉴 컨피던스
- 도파민형 인간
- Container
- 쿠버네티스
- 수부타이
- HTML
- Infresh
- Today
- Total
Hi
프로토타입 체이닝 본문
프로토타입 체이닝
프로토타입의 두 가지 의미
자바스크립트는 프로토타입 기반의 객체지향 프로그래밍을 지원
OOP 상속에 근간이 되는 프로토타입과 프로토타입 체이닝. (자바스크립트는 클래스 개념이 없다)
'프로토타입' 객체 : 생성된 객체의 부모 객체
자바스크립트의 모든 객체는 자신의 부모인 프로토타입 객체르 가리키는 참조 링크 형태의 숨겨진 프로퍼티가 있다.
이러한 링크를 암묵적 프로토타입 링크라 부른다. == [[Prototype]] 링크
함수 객체의 prototype 프로퍼티와 객체의 숨은 프로퍼티인 [[Prototype]] 링크를 구분해야 한다.
// Person 생성자 함수
function Person(name) {
this.name = name;
}
// foo 객체 생성
var foo = new Person('foo');
console.dir(Person);
console.dir(foo);
객체 리터럴 방식으로 생성된 객체의 프로토타입 체이닝
프로토타입 체이닝 : 자바스크립트에서 객체는 자신의 프로퍼티 뿐만이 아니라, 자신의 부모 역할을 하는 프로토타입 객체의 프로퍼티 또한 마치 자신의 것처럼 접근하는 게 가능.
이것을 가능하게 하는 것이 프로토타입 체이닝
var myObject = {
name: 'foo',
sayName: function() {
console.log('My Name is ' + this.name);
}
}
myObject.sayName();
console.log(myObject.hasOwnProperty('name'));
console.log(myObject.hasOwnProperty('nickName'));
myObject.sayNickName();
[출력결과]
My Name is foo
true
false
Uncaught TypeError: Object #<Object> has no method 'sayNickName'
hasOwnProperty() 메서드 : 이 메서드를 호출한 객체에 인자로 넘긴 문자열 이름의 프로퍼티나 메서드가 있는지 체크하는 자바스크립트 표준 API 함수
프로토타입 체이닝 : 특정 객체의 프로퍼티나 메서드에 접근하려고 할 때,
해당 객체에 접근하려는 프로퍼티 또는 메서드가 없다면
[[Prototype]] 링크를 따라 자신의 부모 역할을 하는 프로토타입 객체의 프로퍼티를 차례대로 검색하는 것
생성자 함수로 생성된 객체의 프로토타입 체이닝
자바스크립트에서 모든 객체는 자신을 생성한 생성자 함수의 prototype 프로퍼티가 가리키는 객체를 자신의 프로토타입 객체(부모 객체)로 취급한다.
// Person() 생성자 함수
function Person(name, age, hobby) {
this.name = name;
this.age = age;
this.hobby = hobby;
}
// foo 객체 생성
var foo = new Person('foo', 30, 'tennis');
// 프로토타입 체이닝
console.log(foo.hasOwnProperty('name')); // true
//Person.prototype 객체 출력
console.dir(Person.prototype);
프로토타입 체이닝의 종점
object.prototype에서 프로토타입 체이닝이 끝난다.
모든 자바스크립트 객체는 프로토타입 체이닝으로,
Object.prototype 객체가 가진 프로퍼티와 메서드에 접근하고, 서로 공유가 가능하다.
기본 데이터 타입 확장
Object.prototype, String.prototype 등과 같이,
표준 빌트인 프로토타입 객체에도 사용자가 직접 정의한 메서드들을 추가하는 것을 허용한다.
String.prototype.testMethod = function() {
console.log('This is the String.prototype.testMethod()');
};
var str = "this is test";
str.testMethod(); // 이게 가능하다.
## 프로토타입도 자바스크립트 객체다
// Person() 생성자 함수
function Person(name) {
this.name = name;
}
// foo 객체 생성
var foo = new Person('foo');
foo.sayHello(); // <- 정의 되어 있지 않기에 에러 남
// 프로토타입 객체에 sayHello() 메서드 정의
Person.prototype.sayHello = function() {
console.log('Hello');
}
foo.sayHello(); // Hello
프로토타입 메서드와 this 바인딩
프로토타입 객체는 메서드를 가질 수 있다 (프로토타입 메서드)
메서드 호출 패턴에서의 this는 그 메서드를 호출한 객체에 바인딩된다는 것을 기억하자
ex)프로토타입 메서드와 this 바인딩
// Person() 생성자 함수
function Person(name) {
this.name = name;
}
// getName() 프로토타입 메서드
Person.prototype.getName = function() {
return this.name;
};
// foo 객체 생성
var foo = new Person('foo');
console.log(foo.getName()); // (출력값) foo
// Person.prototype 객체에 name 프로퍼티 동적 추가
Person.prototype.name = 'person';
console.log(Person.prototype.getName()); // (출력값) person
디폴트 프로토타입은 다른 객체로 변경이 가능하다
디폴트 프로토타입 객체 : 함수가 생성될 때 같이 생성, 함수의 prototype 프로퍼티에 연결된다.
디폴트 프로토타입 객체를 다른 일반 객체로 변경하는것이 가능하다.
// Person() 생성자 함수
function Person(name) {
this.name = name;
}
console.log(Person.prototype.constructor); //Person() 생성자 함수를 가리킨다.
// foo 객체 생성
var foo = new Person('foo');
console.log(foo.country); // undefined
// 디폴트 프로토타입 객체 변경
Person.prototype = {
country : 'korea'
};
console.log(Person.prototype.constructor); // Object() 생성자 함수가 출력된다.
// bar 객체 생성
var bar = new Person('bar');
console.log(foo.country); //undefined
console.log(bar.country); //Korea
console.log(foo.constructor); // Person() 생성자 함수
console.log(bar.constructor); // Object() 생성자 함수
객체의 프로퍼티 읽기나 메서드를 실행할 때만 프로토타입 체이닝이 동작한다
객체의 특정 프로퍼티를 읽으려고 할 때, 프로퍼티가 해당 객체에 없는 경우 프로토타입 체이닝이 발생한다.
반대로 객체에 있는 특정 프로퍼티에 값을 쓰려고 한다면 이때는 프로토타입 체이닝이 일어나지 않는다.
// Person() 생성자 함수
function Person(name) {
this.name = name;
}
Person.prototype.country = 'Korea';
var foo = new Person('foo');
var bar = new Person('bar');
console.log(foo.country); // Korea
console.log(bar.country); // Korea
foo.country = 'USA';
console.log(foo.country); // USA
console.log(bar.country); // Korea
'WEB(웹) > javascript' 카테고리의 다른 글
실행 컨텍스트 생성 과정 (0) | 2018.07.03 |
---|---|
실행 컨텍스트 개념 (0) | 2018.07.03 |
이벤트 발생 객체와 이벤트 객체 (0) | 2018.07.01 |
이벤트 개념 잡기 (0) | 2018.07.01 |
(javascript) html 내용중 전의 내용을 가지고 온다. (0) | 2018.06.30 |