My Guide to Javascript Objects with Functions in Them

In the open source code I’m using, there are lots of functions declared like this:

onNewParticipant: function(numberOfViewers) {
document.title = ‘Viewers: ‘ + numberOfViewers;
},

In larger projects where you want to scope as much as possible to prevent overusing variable and function names, you want to create objects that have functions inside of them.

People on StackOverflow informally explain here that writing loose functions willy nilly is “90s”.

More formally, Mozilla explains the many ways you can write objects and functions here. They say that a method is a function associated with an object. Said another way, methods are properties of objects. These special types of functions are defined the same ways as normal functions, except they have to be assigned as the property of an object.

Below this example starts with the object’s name, the method name I want, and the function name I use for the method name.

objectName.methodname = functionName;

var myObj = {
  myMethod: function(params) {
    // ...do something
  }

  // OR THIS WORKS TOO

  myOtherMethod(params) {
    // ...do something else
  }
};

You can then call the method in the context of the object as follows:

object.methodname(params);