class vs factory : class freeze and arrow
by Cristi Salcescu
HTML
<button id="btn">Click</button>
Babel + JSX
function frozen(targetClass) {
Object.freeze(targetClass);
Object.freeze(targetClass.prototype);
}
@frozen
class TodoModel {
constructor(){
this.todos = [];
this.lastChange = null;
}
addToPrivateList(){ console.log("addToPrivateList"); }
add() { console.log("add"); }
reload(){
setTimeout(() => {
console.log(this.todos); //undefined
}, 0);
}
}
//Object.freeze(TodoModel.prototype);
var todoModel = new TodoModel();
//no encapsulation
console.log(todoModel.todos); //[]
console.log(todoModel.lastChange) //null
todoModel.addToPrivateList(); //addToPrivateList
//immutable methods
todoModel.add = function() { console.log("a new add"); }
todoModel.add(); //add
//this loosing context
todoModel.reload(); //undefined
$("#btn").click(todoModel.reload); //undefined