Last active
October 3, 2017 08:02
-
-
Save dmjcomdem/8dd4037bd6df75693ea390706b505562 to your computer and use it in GitHub Desktop.
example encapsulation on js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const TodoList = (function() { | |
/* | |
* todos[{id, title, completed}, ...] | |
*/ | |
let todos = []; | |
return class { | |
constructor() { | |
this.init(); | |
} | |
init() { | |
Object.defineProperties(this, { | |
'todos': { | |
get: function() { | |
return Object.freeze(todos); | |
}, | |
enumerable: true, | |
confugurable: false | |
} | |
}) | |
} | |
add(titleTodo) { | |
todos.push({id: (todos.length + 1) , title: titleTodo, completed: false }); | |
} | |
edit(id, data) { | |
for(let i = 0; i < todos.length; i++) { | |
let todo = todos[i]; | |
if(todo.id == id) { | |
todo.title = data.title || todo.title; | |
todo.completed = data.completed || todo.completed | |
break; | |
} | |
} | |
} | |
remove(id) { | |
for(let i = 0; i < todos.length; i++) { | |
let todo = todos[i]; | |
if(todo.id == id) { | |
todos.splice(i, 1) | |
break; | |
} | |
} | |
} | |
} | |
})(); | |
let todo = new TodoList(); | |
todo.add('JavaScript'); | |
todo.add('HTML'); | |
todo.remove(2); | |
todo.add('CSS'); | |
todo.edit(1, {completed: true}); | |
console.log(todo); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment