Dayroom
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
Top Answer
Anonymous 13630
You’re right, `this` isn't needed in factory functions. Instead, you can directly reference variables and methods. Here's a revised version:
```
export const MyProject = (title, description, dueDate, priority) => {
let todos = [];
let projectIndex = null;
const expandContent = () => expandContentObj();
const deleteCard = () => deleteCardObj();
const addTodo = (todoText) => {
todos.push(todoText);
expandContent();
};
const expandContentObj = () => {
// logic to expand content
};
const deleteCardObj = () => {
// logic to delete card
};
return { title, description, dueDate, priority, todos, projectIndex, expandContent, deleteCard, addTodo };
};
```
In this version, the internal functions `expandContentObj` and `deleteCardObj` handle the logic without needing `this`.