2014-04-23 2 views
5

이유는 다음과 같이 구글 폐쇄 도서관에서 goog.inherits를 않습니다Javascript 상속을 수행 할 때 임시 생성자를 만드는 이유는 무엇입니까?

goog.inherits = function(childCtor, parentCtor) { 
    function tempCtor() {}; 
    tempCtor.prototype = parentCtor.prototype; 
    childCtor.superClass_ = parentCtor.prototype; 
    childCtor.prototype = new tempCtor(); 
    childCtor.prototype.constructor = childCtor; 
}; 

오히려 tempCtor가 어떤 혜택을 제공합니까

goog.inherits = function(childCtor, parentCtor) { 
    childCtor.superClass_ = parentCtor.prototype; 
    childCtor.prototype = new parentCtor(); 
    childCtor.prototype.constructor = childCtor; 
}; 

보다?

+0

둘 다 * childCtor * 인스턴스의 상속 체인에 쓸모없는 객체를 추가합니다. 첫 번째 경우에는 해당 객체가 빈 함수 객체입니다. 두 번째에서는 full * parentCtor * 인스턴스입니다. 따라서 첫 번째가 더 효율적이라고 볼 수 있습니다 (단 하나만 필요하지만 새 빈 함수가 매번 생성되지만). 여기 – RobG

+0

은 흥미로운 읽기입니다. http://bolinfest.com/javascript/inheritance.php – dekdev

답변

5

parentCtor에 초기화 코드가 있고 최악의 경우 일부 인수가 필요한 경우 코드가 예기치 않게 실패 할 수 있습니다. 그래서 더미 함수를 만들어서 상속합니다.

2

리터럴 객체 인스턴스에 대한 참조 사용과 관련하여 다른 함수 인스턴스를 삽입하여 childCtor의 프로토 타입과 parentCtor의 프로토 타입의 실제 인스턴스를 분리합니다.

1

thefheyeye 거의 대답합니다. 첫 번째는 좀 더 효율적으로 볼 수 있지만, 하나의 일시적 생성자가 초기화 중에 생성 된 경우보다 효율적으로 만들 수 있습니다, 의 각 호출에없는 사람은 상속 :

goog.inherits = (function() { 
    function tempCtor(){} 
    return function(childCtor, parentCtor) { 
    tempCtor.prototype = parentCtor.prototype; 
    childCtor.superClass_ = parentCtor.prototype; 
    childCtor.prototype = new tempCtor(); 
    childCtor.prototype.constructor = childCtor; 
    }; 
}()); 

나는 차이가 측정 가능한 것을 의심 , 때때로 CPU주기와 바이트 수를 절약하기 위해 따뜻한 내부 광선을 제공합니다.