Dependency Injection with classes which are created often
Am I better off just importing an instantiated version of Convert into Person.js and referencing it directly? I know that will work, but I was trying to avoid coupling the two classes without a nice way to override. I definitely don't like what I have written here, since Convert will be defined on each Person, which is worse than coupled classes in my opinion.


There is nothing wrong with requiring a data conversion service. The problem is coupling the conversion service with the Person class. This coupling should occur in the Factory class instead.

Furthermore, you haven't coupled the classes together. ECMA Script is a dynamically typed language. At worst you've coupled the Person class to an object supporting the same public interface as the Convert class.

Solving this dilemma is pretty simple. The data conversion should happen in the factory:

factory.js

import {Person} from './person.js';

export class Factory {

    constructor({ convert }) {
        this.convert = convert;
    }

    person(obj) {
        obj.first = this.convert.toString(obj.first);
        obj.last = this.convert.toString(obj.last);

        return new Person(obj);
    }
}


person.js

export class Person {
    constructor({ first, last }) {
        this.first = first;
        this.last = last;
    }
}


This keeps your Person constructor clean and straight forward. The messiness of converting data types is encapsulated in the Factory class where it belongs, and the Person class no longer has a dependency on the Convert class.