Home > UI Developer > Aren’t classes the right way to create objects in JavaScript?

Aren’t classes the right way to create objects in JavaScript?


No.

There are several right ways to create objects in JavaScript. The first and most common is an object literal. It looks like this (in ES6):

// ES6 / ES2015, because 2015.

let mouse = {
  furColor: 'brown',
  legs: 4,
  tail: 'long, skinny',
  describe () {
    return `A mouse with ${this.furColor} fur,
      ${this.legs} legs, and a ${this.tail} tail.`;
  }
};

Of course, object literals have been around a lot longer than ES6, but they lack the method shortcut seen above, and you have to use `var` instead of `let`. Oh, and that template string thing in the `.describe()` method won’t work in ES5, either.

You can attach delegate prototypes with `Object.create()` (an ES5 feature):

let animal = {
  animalType: 'animal',
  
  describe () {
    return `An ${this.animalType}, with ${this.furColor} fur, 
      ${this.legs} legs, and a ${this.tail} tail.`;
  }
};

let mouse = Object.assign(Object.create(animal), {
  animalType: 'mouse',
  furColor: 'brown',
  legs: 4,
  tail: 'long, skinny'
});

Let’s break this one down a little. `animal` is a delegate prototype. `mouse` is an instance. When you try to access a property on `mouse` that isn’t there, the JavaScript runtime will look for the property on `animal` (the delegate).

`Object.assign()` is a new ES6 feature championed by Rick Waldron that was previously 
implemented in a few dozen libraries. You might know it as `$.extend()` from jQuery or 
`_.extend()` from Underscore. Lodash has a version of it called `assign()`. 
You pass in a destination object, and as many source objects as you like, separated by
 commas. It will copy all of the enumerable own properties by assignment from the source 
objects to the destination objects with last in priority. If there are any property name
 conflicts, the version from the last object passed in wins.

`Object.create()` is an ES5 feature that was championed by Douglas Crockford so that we could attach delegate prototypes without using constructors and the `new` keyword.

I’m skipping the constructor function example because I can’t recommend them. I’ve seen them abused a lot, and I’ve seen them cause a lot of trouble. It’s worth noting that a lot of smart people disagree with me. Smart people will do whatever they want.

 

Categories: UI Developer
  1. No comments yet.
  1. No trackbacks yet.

Leave a comment