Chris
Chris

Reputation: 14260

js get chain of constructor names

I generate a chain of constructor names based on inheritance:

class Person {
}

class User extends Person {
}

$userClassIdentifier = generateIdentifier(User.constructor)     
// userClassIdentifier = 'Person.User'

function generateIdentifier(constructor) {
        if (constructor.prototype && constructor.prototype.__proto__
            && constructor.prototype.__proto__.constructor && constructor.prototype.__proto__.constructor.name) {
            return  `${constructor.prototype.__proto__.constructor.name}.${constructor.name}`
        }
        return constructor.name
}

this works for one level of inheritance. But it seems very hacky/ugly. Is there a nicer way to do it and to make it work for an unknown number of levels deep?

Upvotes: 1

Views: 38

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1075925

If I have SUV extending Car extending Vehicle I expect 'Vehicle.Car.SUV'

I'd use getPrototypeOf and a loop, starting with the constructor you want to start with, and ending when that constructor's prototype is Function.prototype or null:

function getLineage(ctor) {
  let name = ctor.name;
  while ((ctor = Object.getPrototypeOf(ctor)) != Function.prototype && ctor) {
    name = ctor.name + "." + name;
  }
  return name;
}

class Vehicle { }
class Car extends Vehicle { }
class SUV extends Car { }

console.log(getLineage(SUV));

One suggestion I'd make, though, would be to use a different separator rather than ., as . seems to suggest that (say) SUV is a property of Car, which of course it isn't. :-)

Upvotes: 3

Related Questions