2015년 6월 16일 화요일

javascript prototype

javascript prototype 에 대한 고찰

        Selector.index = 0;
 Selector.prototype.getIndex = function(){  
  return this.constructor.index++;
 };
 function Selector(){
  this.index = this.getIndex();
  
  alert(this.constructor.index);
  
  this.print = function(){
   alert(this.index);
  };
 }
 
 var a1 = new Selector();





나는 여러개의 Selector 생성시 내부적으로 셀렉터의 ID를 관리하고 싶었다. 그래서 위 처럼 this.constructor.index++ 을 사용했는데..
이처럼 해도 되는거는.. this의 constructor 는 function Selector 일거고 Selector 라는 함수원형에 index가 추가 선언되어 있으니 
접근가능한것이라고 이해했음. 그냥 Selector.index++ 로 해도 된다.

prototype에 대해서.. 
함수원형을 만들때 원형 자체는 객체가 아니다. 객체를 확장시킬시에 사용되는 틀에 불과하며 게다가 내부적으로 이미 prototype 즉
객체를 확장시키기 위한 객체가 만들어져 링크되어있다. 이것이 바로 prototype 이다. 

그러므로 Selector.prototype.getIndex 을 선언했을때 new 키워드를 사용해서 객체를 생성하면 Selector 의 prototype 객체를 사용해서 
만들어지므로 getIndex가 확장된다. 그리고 new 당시 생성자 즉 Selector() 에서 정의된 내용은 prototype의 constructor 에 링크되어있다. 
즉 서로 맞물려있는 관계라고 볼수있따.