Comparing JavaScript object creation patterns: Regular vs IIFE approach

Hey folks! I’m trying to wrap my head around different ways to create objects in JavaScript. I’ve got two code examples here and I’m not sure what makes them different or if one is better than the other.

The first one looks like a regular constructor function:

function Person(name) {
  this.name = name;
}

Person.prototype.sayHi = function() {
  console.log('Hello, ' + this.name);
};

let bob = new Person('Bob');
bob.sayHi();

And the second one uses an IIFE (I think that’s what it’s called?):

var Person = (function() {
  function Person(name) {
    this.name = name;
  }
  
  Person.prototype.sayHi = function() {
    console.log('Hello, ' + this.name);
  };
  
  return Person;
})();

let alice = new Person('Alice');
alice.sayHi();

Can someone explain the pros and cons of each approach? When would you use one over the other? Thanks!

I’ve used both approaches in different projects, and each has its place. The regular constructor is my go-to for simple objects. It’s quick to write and easy to understand. The IIFE pattern, though, has saved my bacon a few times when working on larger projects with multiple developers. It helps prevent namespace collisions and keeps implementation details hidden.

That said, these days I find myself gravitating towards ES6 classes more often. They offer a nice balance between readability and functionality. Plus, they play well with TypeScript if you’re into that.

One thing to keep in mind: performance can vary slightly between these methods, especially when creating many instances. In most cases, the difference is negligible, but it’s worth benchmarking if you’re working on performance-critical code.

hey charlielion, i think the regular constructor is more straightforward, while the iife adds a bit extra encapsulation.

honestly, both work but these days i lean towards classes for clarity and modern style.

The regular constructor approach is more common and easier to understand, especially for beginners. It’s straightforward and gets the job done. The IIFE pattern, on the other hand, provides a bit more privacy and can help avoid polluting the global scope. It’s useful when you want to create a closure and keep some variables or functions private.

In modern JavaScript, however, many developers prefer using the class syntax introduced in ES6. It’s more intuitive if you’re coming from other object-oriented languages and provides a cleaner way to define objects and their methods. Ultimately, the choice depends on your specific use case and coding style preferences.