How to create Factory Functions instead of using Classes

Good day. I’m making a todo list app. Instead of classes, I want to use factory functions.

Original code with classes:

export class MyProject {
    constructor(title, description, dueDate, priority) {
        this.title = title;
        this.description = description;
        this.dueDate = dueDate;
        this.priority = priority;
        this.todos = [];
        this.projectIndex = null;

        this.expandContent = () => expandContent(this);
        this.deleteCard = () => deleteCard(this);
        this.addTodo = (todoText) => {
            this.todos.push(todoText);
            this.expandContent();
        };
    }
}

I tried using factory functions:

export const MyProject = (title, description, dueDate, priority) => {
    let todos = [];
    let projectIndex = null;

    const expandContent = () => expandContent(this);
    const deleteCard = () => deleteCard(this);
    const addTodo = (todoText) => {
        todos.push(todoText);
        expandContent();
    }

    return {title, description, dueDate, priority, todos, projectIndex, expandContent, deleteCard, addTodo}
};

I’ve acknowledged, that this is not necessary in factories, I’m not really sure how not to use them in expandContent and deleteCard functions

Hello, you could take Codecademy’s Introductory offer for this. I did and it covers alot about helper and factory functions. The question is why do this I guess or what is better or easer about them.
link: javascript - Constructor function vs Factory functions - Stack Overflow

1 Like

Not sure why you have stand-alone functions called by methods. It doesn’t help you have named them the same. Why don’t you just make them methods if they need the data in the class?

Anyway, if they are expecting this you need to pass them the return object. But do the functions need all of this or just parts of it? The names of the functions doesn’t seem to suggest they would need all of this.

If you make the factory return a single object you can have the data as properties and the functions as methods with access to this

const createUser = ({ firstName, lastName, email }) => ({
  firstName,
  lastName,
  email,
  fullName() {
    return `${this.firstName} ${this.lastName}`;
  },
});

const user1 = createUser({
  firstName: "John",
  lastName: "Doe",
  email: "john@doe.com",
});

console.log(user1.fullName()); // John Doe
1 Like