2017-09-15 67 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() 

未经测试,但我一直在我的代码中使用类似的概念。

享受!

相关问题