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();
newwith it to get an instance. That's your first example. The second one is doing a similar thing to what would happen if you callbunny = new Rabbit()as you are replacing this withbunny = RabbitFactory()yet the latter is less flexible. What the article suggests is to use less code, so what you should do is something likebunny = Object.create(rabbit)