2 ms·
> Um, what? Sorry for the confusion, the ES5 example looked like a "factory" function, so I assumed that was what he meant. You do not have to wrap the constru
by z3t4 10y ago
> Um, what?
Sorry for the confusion, the ES5 example looked like a "factory" function, so I assumed that was what he meant. You do not have to wrap the constructor function in another function! ...
function Animal(name) {
// This code is run when the object is created. No need to wrap another function around Foo
var animal = this;
animal.name = name;
}
Animal.prototype.speak = function speak() {
var animal = this;
console.log(animal.name + ' makes a noise.');
}
Here is a "factory" function:
function AnimalFactory(name) {
var animalName = name;
function speak() {
console.log(animalName + ' makes a noise.');
}
return {speak: speak}
}
var animal = AnimalFactory('Animal'); // You can omit new
animal.speak(); // animal makes a noise
setTimeout(animal.speak, 1000); // you can also do this