CodeNewbie Community 🌱

Abdulrahman Noble
Abdulrahman Noble

Posted on

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();
        };
    }
}

Enter fullscreen mode Exit fullscreen mode

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}
};

Enter fullscreen mode Exit fullscreen mode

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

Top comments (0)