__proto__ 속성을 가지고 있다 let a = {}; let a = new Object();
function Person(){} let Person = new Function();
function Ultra() {};
__proto__ 프로퍼티를 가진 객체이다 function Ultra() {}; Super = new Ultra(); -> prototype: {constructor: ƒ} constructor: ƒ Ultra() __proto__: Object
_proto_가 생성됐다var a = new Date(); Date.prototype.constructor === Date //-> true a.constructor //-> f Date(){} //a를 누가 만든 객체인지 모를 때 constructor 이용 //a는 자체적으로 constructor를 가지고 있지 않기 때문에 //__proto__를 따라 constructor function의 prototype object로 //가서 거기에 있는 constructor라는 프로퍼티를 통해서 //자신을 생성해준 생성자를 뱉어낸다 b = new d.constructor() / b = new Date() //-> 같은 코드이다
__proto____proto__는 prototype link이다 __proto____proto__ 속성은 객체를 생성한 함수의 prototype object를 가리킨다 function Ultra() {}; Ultra.prototype.name = 'bora'; Ultra.prototype.age = 20; Super = new Ultra(); console.log(Super.name); -> bora console.log(Super.age); -> 20
__proto__속성 즉 prototype link 때문function Ultra() {}; Ultra.prototype.name = 'bora'; Ultra.prototype.age = 20; Super = new Ultra(); Sub = new Ultra(); Sub.name = 'gogo'; Sub.age = 30; console.log(Super.name); -> 'bora' console.log(Super.age); -> 20 console.log(Sub.name); -> 'gogo' console.log(Sub.age); -> 30
__proto__와 연결된 prototype object를 참조 __proto__가 가리티는 링크르 따라 부모 역할을 하는 prototype object의 프로퍼티나 메소드를 타고 올라가는 것 - prototype 체이닝 function Ultra() {} Ultra.prototype.ultraProp = true; function Super() {} Super.prototype = new Ultra(); function Sub() {} Sub.prototype = new Super(); var o = new Sub(); console.log(o.ultraProp);
- Ultra 함수를 정의한 후 prototype 객체 안에 ultraProp와, Ultra()라는 constructor가 생성됐다
- Sub라고하는 함수는 객체이기 때문에 프로퍼티를 가지고 잇을 수 있다
- 그 프로퍼티 중에서 prototype이라는 특수한 프로퍼티가 있어서 이 prototype이라는 프로퍼티 안에는 어떠한 객체가 정의가 돼 있다 (객체가 들어가 있다)
- Sub.prototype.name = 'baro'
-> prototype 객체 안에 name이라는 프로퍼티가 있고 그 값이 baro다- 그렇게 객체를 저장해 놓은 후 나중에 new를 이용해서 생성자를 호출하게 되면 javascript는 이 생성자 함수(Sub)의 prototype 프로퍼티에 저장돼 있는 객체를 꺼내서 그것을 return해 준다
- Sub.prototype = new Super();
-> Super 생성자가 만든 객체가 이 안에 들어간다- 서로가 서로에 연결되어 있는 것을 Prototype chain이라고 한다
function Person(name, first, second){ this.name = name; this.first = first; this.second = second; }; Person.prototype.sum = function() { return 'prototype : '+ (this.first + this.second); } var park = new Person('park', 20, 30); var lee = new Person('lee', 30, 40);
console.log(park.sum()); console.log(lee.sum());-> prototype : 50
prototype : 70
function Person(name, first, second){ this.name = name; this.first = first; this.second = second; }; Person.prototype.sum = function() { return 'prototype : '+ (this.first + this.second); } var park = new Person('park', 20, 30); park.sum = function() { return 'this : '+ (this.first + this.second); } var lee = new Person('lee', 30, 40); console.log(park.sum()); console.log(lee.sum());-> this : 50
prototype : 70