Class vs Factory Function
by LyndseyB
HTML
<input type="button" id="btn" value="Click Me" />
JavaScript
var Dog = function() {
this.sound = "woof";
this.talk = function() {
//console.log(this);
console.log(this.sound);
}
};
//console.log(new Dog().sound); // sound isn't private!
var factoryDog = function() {
var sound = "woof",
talk = function() {
console.log(sound);
}
return {
talk: talk
}
};
//console.log(factoryDog.sound); // sound is private, so it is undefined!
var sniffles = new Dog(),
pudsy = factoryDog(),
btn = document.getElementById('btn');
/*
btn.addEventListener('click', sniffles.talk); // this is the btn element, not Dog
btn.addEventListener('click', sniffles.talk.bind(sniffles)); // ensure sniffles is this so that dog woofs!
*/
btn.addEventListener('click', pudsy.talk);