0

if i take class TodoItem item outside the function and instead write return new TodoItem(), i can not access uid and other properties. and i dont know why as the object is being created inside the function so it should have took that in to scope too? i think.

function TodoItemFactory(todoItem = {}) {
    const uid = todoItem.uid || utils.generateRandomString()
    const createdTime = todoItem.createdTime || new Date()
    let title = todoItem.title || ''
    let modifiedTime = todoItem.modifiedTime || createdTime
    let isCompleted = todoItem.isCompleted || false
    let isDeleted = todoItem.isDeleted || false
    
    return new (class TodoItem {

        setTitle(newTitle) {
            title = newTitle
            this.setModifiedTimeToCurrentTime()
        }
    
        setModifiedTimeToCurrentTime() {
            modifiedTime = new Date()
        }
    
        setIsCompleted(bool) {
            isCompleted = bool
            this.setModifiedTimeToCurrentTime()
        }
    
        setIsDeleted(bool) {
            isDeleted = bool
            this.setModifiedTimeToCurrentTime()
        }
    
        getAllProperties() {
            return {
                uid, createdTime, modifiedTime, isDeleted, isCompleted, title
            }
        }
    })()
}
Abhay Soni
  • 21
  • 3
  • 2
    JavaScript has **lexical scope**, not dynamic scope. If you move the class definition outside the function then `uid`, etc is not in scope of the class anymore. FWIW, there is no need to use a class here at all. Using a class to create just a single instance is wrong most of the time. On the other hand this example looks incomplete so it's difficult to give suggestions for how to really improve this. – Felix Kling Sep 17 '20 at 06:59
  • What Felix said. [Don't use `new class { … }`.](https://stackoverflow.com/q/38739499/1048572). – Bergi Sep 17 '20 at 22:31

0 Answers0