Maximus Maximus - 1 year ago 67
Javascript Question

How to write JavaScript with factory functions

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
requirement, global pollution danger and awkward
limitations (including that annoying initial capitalized letter

JavaScript doesn’t need constructor functions because any
function can return a new object. With dynamic object extension,
object literals and
, we have everything we
need — with none of the mess. And
behaves 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();

Answer Source

No, that is wrong. You should not use Object.setPrototypeOf, better use Object.create (though it makes no difference for the result). And if you create the prototype from an object literal every time, it loses all of its sharing advantages, so you should either drop that completely or move it outside the function to make it static. The correct™ way to write the factory function would be

const protoRabbit = {
    getSpeed: function() {
        return this.speed;
function createRabbit() {
    var rabbit = Object.create(protoRabbit);
    rabbit.speed = 3;
    return rabbit;

var rabbit = createRabbit();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download