简体   繁体   中英

javascript access class factory from class instance

Is it possible to access the factory that created current instance from the same instance?

for example:

class Vect {}
class DVect extends Vect{}

const calcFunc = (inst:Vect|DVect) =>{
  let constructorParams = ...
  return new inst.Factory(...constructorParams)
  //note - Factory is not a real method
}

console.log(calcFunc(new Vect))
// will log a Vect instance

console.log(calcFunc(new DVect))
// will log a DVect instance


here I would expect a Vect to be returned if I passed to calcFunc a Vect and DVect if I passed DVect

so, is it possible in javascript?

Try the .constructor property that's on almost every object in JS:

const calcFunc = (inst /*: Vect|DVect */) => {
  let constructorParams = //...
  return new inst.constructor(...constructorParams)
}

(Edge case: objects created by Object.create(null) won't have a .constructor property. But objects created by doing new Vect , new DVect , new of any class {...} should all have a .constructor .)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM