Skip to main content
Code Review

Return to Answer

Commonmark migration
Source Link

#Objects not classes

Objects not classes

##Many ways to create objects

Many ways to create objects

##Which to use

Which to use

##Questions

Questions

#Objects not classes

##Many ways to create objects

##Which to use

##Questions

Objects not classes

Many ways to create objects

Which to use

Questions

Source Link
Blindman67
  • 22.8k
  • 2
  • 16
  • 40

#Objects not classes

In JavaScript there are no classes only Objects. The token class is just an alternative syntax (often referred to as syntactical sugar) for defining an Object.

##Many ways to create objects

The following shows two very similar objects defined using class syntax and standard syntax

class Foo {
 constructor() { this.bar = "A" }
 poo() {}
}
function Foo() { this.bar = "B" }
Foo.prototype = { poo() {} }

You can also define the object as...

function Foo() {
 this.bar = "C";
 this.poo = function(){};
}

or...

const Foo = {
 bar: "D",
 poo() {},
};

or...

const Foo = () => ({
 bar: "D",
 poo() {},
});

...and there are many more ways to define an object.

##Which to use

Which you use is very dependent on how you use the object.

  • Is there more than one instance?
  • What is the life time of an instance?
  • Do you need to extend the object? (polymorphic)
  • What level of encapsulation is required?
  • Do you need an inheritance model?
  • How do you wish to instantiate the object?
  • What is the legacy support requirement?

To know the language you must be proficient in all its forms, and know what is the appropriate code to use.

##Questions

Is this something that would benefit from being a class?

No as there are no classes in JavaScript.

A LightboxCollection class for example? That has an array Lightbox?

You can create a collection from an Array. Assuming you are using only a single instance. It has all the functions that an array has plus what ever you want to add. Eg add

const LightboxCollection = (() => {
 return Object.assign([],{
 add(lightBox){ this.push(lightBox) },
 });
})();

Or encapsulate the array, so you can maintain the array state (vet items and expose only functions that you need)

const LightboxCollection = (() => {
 const items = [];
 return Object.freeze({
 add(lightBox) { lightBox instanceof LightBox && items.push(lightBox) },
 get length() { return items.length },
 set length(len) { items.length = len < items.length ? len : items.length },
 forEach: items.forEach.bind(items),
 });
})(); 
default

AltStyle によって変換されたページ (->オリジナル) /