사진 출처 -> 생활코딩 prototype vs __proto____(Youtube)
사진 설명( 프로토타입의 기초 설명)
-> 예를 들어 Person이라는 생성자를 만들게 된다면
그아래에 자동적으로 prototype이라는 프로퍼티가 생성되게된다.
그 프로퍼티는 Person 생성자가 생성되면서 자동으로 생성되는
Constructor prototype을 가리키게되고, 그곳에는 자동적으로
constructor라는 프로퍼티가 생기면서 원래의 생성자(Constructor)를 가리키게된다. new를 사용하여서 새로운 인스턴스를 만들게 되고,
그 인스턴스에는 __proto__라는 Constructor prototype을 가리키는 값이 만들어 지게된다.
var Person = function(name){
this._name = name;
}; //생성자 함수
Person.prototype.getName = function(){
return this._name;
}; //생성자 함수의 프로토타입에 메서드
var suzi = new Person('suzi'); //Person의 인스턴스를 생성
suzi.__proto__.getName();
//자동으로 인스턴스의 __proto__가 생성되고 __proto__는
Person.prototype을 가리키게된다.
하지만 console.log를 찍었을때 undefinde가 나타나게되는데,
이는 prototype에는 getName이라는 메서드는 있으나, this._name이
없기때문에 나타나는 현상.
var suzi = new Person('suzi');
suzi.__proto__._name = 'SUZI__proto__';
suzi.__proto__.getName(); // SUZI__proto__
//__proto__ 없이 인스턴스에서 곧바로 메서드를 사용한다면
var suzi = new Person('suzi' , 28);
suzi.getName(); // Suzi
var iu = new Person('Jieun', 28);
iu.getName(); // Jieun
suzi.__proto__.getName
-> suzi(.__proto__).getName
-> suzi(.getName)
위의 3가지는 모두다 같은것을 의미한다.
var Constructor = function(name){
this.name = name;
}
Constructor.prototype.method1 = function() {};
Consturctor.prototype.property1 = 'Constructor Prototype Property';
var instance = new Constructor('Instance');
console.dir(Constructor);
console.dir(instance);
상위의 prototype과 __proto__안에 같은
method1(): f(), property1 : "Constructor Prototype Property"가 있는것을 확인할수있다.
즉 __proto__가 prototype을 참고하고있다는것을 알수있다.
인스턴스가 동일한 이름의 프로퍼티 또는 메서드를 가지고있는 상황이라면
이때는 메서드 오버라이드가 일어나게된다.
var Person = function(name){
this.name = name;
};
Person.prototype.getName = function(){
return this.name;
};
var iu = new Person('지금');
iu.getName = function(){
return '바로' + this.name;
};
console.log(iu.getName()); // 바로 지금
Person 생성자의 prototype에 getName을 선언해주었는데
iu라는 인스턴스에 새로운 getName을 선언하여서 호출하였더니
인스턴스의 메소드가 실행되었다.
이렇게 같은 이름의 프로퍼티나 메소드가 잇을경우에는 가까운 순서대로
실행이된다. 즉 오버라이드가 일어나게되는것.
객체의 내부구조
배열의 내부구조
객체에는 __proto__가 하나밖에 없었는데, 배열에는
__proto__안에 __proto__를 하나더 가지고있다. 이유가 무엇일까?
배열의 __proto__도 하나의 객체이기때문이다.
Object -> Object.prototype
Array -> Array.prototype
Object, Object.prototype -> Array.prototype을 따른다
어떤 데이터의 __proto__프로퍼티 내부에서
다시 __proto__프로퍼티가 연쇄적으로 이어진것을
prototype chain이라고하며 이러한 chain을 따라가며 검색하는것을
prototype chaining이라고한다.
!!이내용은 코어 자바스크립트(정재남지음) 책을보고 정리한 내용입니다