I'm reading this article about perils of trying to mimic OOP in JavaScript and there's the following:
In JavaScript, factory functions are simply constructor functions minus the
newrequirement, global pollution danger and awkward limitations (including that annoying initial capitalized letter convention).JavaScript doesn’t need constructor functions because any function can return a new object. With dynamic object extension, object literals and
Object.create(), we have everything we need — with none of the mess. Andthisbehaves just like it does in any other function. Hurray!
Am I right to assume that given this approach we should replace this code:
function Rabbit() {
this.speed = 3;
}
Rabbit.prototype = {
this.getSpeed = function() {
return this.speed;
}
}
var rabbit = new Rabbit();
With this:
function RabbitFactory() {
var rabbit = {
speed: 3
};
Object.setPrototypeOf(rabbit, {
getSpeed: function() {
return this.speed;
}
})
return rabbit;
}
var rabbit = RabbitFactory();