var arr = Array(); //Array란 Constructor로 생성한 instance를 arr변수에 할당
arr.__proto__ === arr === Array.prototype //instance와 constructor에서 prototype에 접근
Array.prototype.constructor = Array //prototype에서 constructor 접근가능
function Person() {
this.name = n;
this.age = a;
}
var iu = new Person('아이유', 25);
var gyurr = new Person('귤', 30);
iu.getAge = function() {
return this.age;
}
gyurr.getAge = function() {
return this.age;
}
위의 소스의 중복을 줄이기 위해 prototype에 getAge함수를 선언하게 되면 각 instance 마다 getAge 함수를 선언하지 않아도 됨.
Person.prototype.getAge = function(){
return this.age;
}
iu.__proto__.getAge(); //NaN -> 왜냐하면 this가 iu.__proto__이기때문
iu.getAge(); //25 -> iu.__proto__와 iu가 같은기능을 하기때문에 this가 iu가 되면서 25 반환
this가 iu.__proto__
이기때문에 반환값이 NaN
이 나오는 문제를 해결하기위해 __proto__
를 생략하여 iu.getAge()
를 실행하게 되면 this가 iu가 되면서 25를 반환