
모던 자바스크립트 Deep Dive
→ 내부 슬롯(ex [[Prototype]])과 내부 메서드(getter,setter)는 ECMAScript 사양에 정의된 대로 구현되어 자바스크립트 엔진에서 실제로 동작하지만 개발자가 직접 접근할 수 있도록 외부로 공개된 객체의 프로퍼티는 아니다.(직접적으로 접근 X)
why? → JavaScript의 안전성과 무결성을 유지하기 위해 설계됨?
const person = {name: "Lee"};
//person 객체는 __proto__ 프로퍼티를 소유하지 않는다.
console.log(person.hasOwnProperty("__proto__")); //false
//__proto__프로퍼티는 모든 객체의 프로토타입 객체인 Object.prototype의 접근자 프로퍼티다.
console.log(Object.getOwnPropertyDescriptor(Object.prototype,"__proto__"));
// { get: [Function: get __proto__], set: [Function: set __proto__], enumerable: false,configurable: true} -> 접근자 프로퍼티
//모든 객체는 Object.prototype의 접근자 프로퍼티 __proto__를 상속받아 사용할 수 있다. 정의될때 자동으로 __proto__가 설정
console.log({}.__proto__ === Object.prototype); //true
const parent = {};
const child = {};
//child의 프로토타입을 parent로 설정
child.__proto__ = parent;
//parent의 프로토타입을 child로 설정
parent.__proto__ = child; //TypeError: Cyclic __proto__ value
→ 서로가 자신의 프로토타입이 되는 비정상적인 프로토타입 체인이 만들어지기 때문에 에러를 발생시킨다
//생성자 함수
function Person(name){
this.name = name;
}
const me = new Person("Lee");
//me 객체의 생성자 함수는 Person이다.
console.log(me.constructor === Person); //true
→ new 연산자로 Constructor를 호출하면 instance가 만들어지는데, 이 instance의 생략 가능한 프로퍼티인 proto는 Constructor의 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()); //바로 지금
delete iu.getName;
console.log(iu.getName()); //지금