2017-09-15 5 views
2

코드를 사용하여 설명하기가 어렵습니다.함수의 프로토 타입을 생성자 자체로 만들기

function Base() {} 
Base.prototype = function() { 
    // I am a constructor 
} 
const baseInstance = new Base() 
const secondInstance = new baseInstance() // baseInstance is not a constructor 

은 내가 생성자에게 .prototype의 명명 된 속성을했다하지만 난 내 코드에서 위의 패턴을 할 수 있도록하려는 경우가 매우 간단 할 것 이해합니다. 가능한가?

답변

0

나는 그것을 해결했다고 생각합니다. 그것은 약간의 해킹입니다. 생성자에 Object.assign()을 잼하십시오.

function Base() { 
    return Object.assign(
     function SecondConstructor() {}, 
     Base.prototype 
    ) 
} 
Base.prototype = function() { 
    // This can now have properties which 
    // will be attached to the constructor 
} 
const baseInstance = new Base() 
// baseInstance is now a constructor 
const secondInstance = new baseInstance() 

테스트되지 않았지만 내 코드에는 비슷한 개념이 사용되었습니다.

즐기십시오!