PROTOTYPE

이남수·2020년 2월 7일
0

prototype, __proto__, constructor관계

  • Constructor
  • instance
  • prototype
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를 반환

profile
큘슈호윤

0개의 댓글