-1

I have two functions that do the same thing (I may be wrong, but seems like they do the same thing in my newbie opinion):

// Factory Function
function createCircle(radius) {
    return {
        radius,
        draw: function() {
            console.log('draw');
        }
    }
}
const newCircle = createCircle(2);
console.log(newCircle);

And

// Constructor Function
function Circle(radius) {
    this.radius = radius;
    this.draw = function() {
        console.log('draw')
    }
}
const another = new Circle(2);
console.log(another);

Are there some pros and cons of these approaches? Just seeking for the opinions of more experienced developers.

1 Answers1

1

For most circumstances I'd say the constructor function is better.

  • It lets you check whether the object is a Circle by using the instanceof operator (i.e. circle instanceof Circle)
  • It makes the code more readable - when someone sees new Circle they know that a class is being instantiated, and they know that it will have a predictable behaviour, whereas for the first case they need to check the function definition (or documentation) of createCircle before they know anything about what this function is returning.
  • You can optimise the constructor a little more - if you define the draw function on the class's prototype (i.e. Circle.prototype.draw = function(){/*etc*/}) then it doesn't get declared each time you call new Circle.

That said, if you're creating an object with just a few properties and no methods then using the first example is perfectly reasonable.

Gorse horse
  • 5,093
  • 1
  • 20
  • 14