[JavaScript] new 연산 자의 작업 원리

1911 단어
var F=function(){
    //this   ,         
};

var p=new F;

new 로 함수 호출 이 발생 했 습 니 다: (1) 새 대상
instance=new Object();

(2) 원형 체인 설정
instance.__proto__=F.prototype;

(3) F 중의 this 을 가리 키 고 instance F 의 함수 체 를 집행 하도록 한다.
(4) 판단 F 의 반환 값 유형: 값 유형 이 라면 버 리 든 지, 되 돌아 오 든 지 instance.인용 형식 이 라면 이 인용 형식의 대상 을 되 돌려 주 고 교체 합 니 다 instance.
주: (1) return 을 쓰 지 않 으 면 return undefined 에 해당 합 니 다. 자바 스 크 립 트 의 함 수 는 모두 이 렇 습 니 다.undefined 는 값 형식 이 므 로 버 리 고 인 스 턴 스 로 돌아 갑 니 다.(2) return this 가 인용 형식의 대상 을 되 돌려 주 는 것 과 같다 면 자신 이 인 스 턴 스 입 니 다. 바 꾸 든 안 바 꾸 든 상관 없습니다.(3) intance 에 대해 서 는 constructor 속성 을 설정 할 필요 가 없습니다. 이 속성 은 intance 의 원형 에 있 습 니 다.
console.assert(!p.hasOwnProperty('constructor'));
console.assert(F.prototype.hasOwnProperty('constructor'));

그리고 임의의 새 함수 가 생 성 되 었 을 때, 원형의 constructor 는 이미 설정 되 어 있 습 니 다.
var G=function(){};
console.assert(G.prototype.hasOwnProperty('constructor'));
console.assert(G.prototype.constructor===G);

따라서 프로 토 타 입 을 다시 할당 할 때 constructor 속성 을 다시 지정 해 야 합 니 다.
F.prototype={
    constructor:F
};

증명:
/* about the constructor

// instance.constructor is exactly instance.__proto__.constructor
function F() { }
console.assert((new F).constructor === F);
console.assert((new F).hasOwnProperty('constructor') === false);
console.assert(F.prototype.hasOwnProperty('constructor') === true);

// so if we change the prototype, we should also change the prototype's constructor.
function F(){}
F.prototype=new G;
F.prototype.constructor=F;

// if not, (new F).constructor===F.prototype.constructor===(new G).constructor===G.prototype.constructor===G;

좋은 웹페이지 즐겨찾기