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 (3)

Collapse
 
tomdanny profile image
Tom Danny

Custom t-shirts can be a fun way to promote coding concepts, like how to create factory functions instead of using classes. Featuring catchy phrases or diagrams that explain this functional programming approach, these shirts can spark conversations among developers at meetups and conferences. By wearing custom t-shirts with programming tips, tech enthusiasts can share their knowledge about creating cleaner, more modular code, encouraging others to explore different coding techniques for better software design.

Collapse
 
alicejenny123 profile image
alicejenny123

I was able to expand my horizons by reading the post, which provided me with an abundance of knowledge.
escape road

Collapse
 
scouring profile image
Abdulrahman Noble

Image description
Do you mean by reading this post?