JavaScript Object Patterns

All object properties in JavaScript are public. There is no explicit way to indicate that a property shouldn’t be accessed from outside. Sometime we don’t want the data to be public. For example, when an object uses a value to determine some sort of state, modify that data without the objects’ knowledge throws the state management process.

One way to avoid this is by using naming conventions. For example, it’s quite common to prefix properties with an underscore (such as _name) when they are not intended to be public. However, there are other ways of hiding data that don’t rely on conventions.

The Module Pattern

There are many different ways to create and compose objects in JavaScript. While JavaScript does not include the formal concept of private properties, we can create data or functions that are accessible only from within an object. For singleton objects, we can use the module pattern to hide data from the outside world. we can use an immediately invoked function expression (IIFE) to define local variables and functions that are accessible only by the newly created object. Privileged methods are methods on the object that have access to private data. We can also create constructors that have private data by either defining variables in the constructor function or by using an IIFE to create private data that is shared among all instances.

var yourObject = (function() {

      // private data variables

      return {
          // public methods and properties
      };
}());

Here we are defining custom type that are keeping their private properties. This is similar to module pattern inside the constructor to create instance-specific private data.

function Student(name) {
            this.name = name;
        }
        Student.prototype = (function () {
            //private variables inside this closure scope
            var age = 25;   
            var myGrades = [93, 95, 88, 0, 55, 91];

            function getAge() {
                return age;
            }
            function growOlder() {
                age++;
            }

            function getAverage() {
                var total = 0;
                for (var i = 0; i < myGrades.length; i++) {
                    total += myGrades[i];
                }
                return avg = (total / myGrades.length);
            }

            function getGradeStatus() {
                var failingGrades = myGrades.filter(function (item) {
                    return item < 70;
                });

                return 'You failed ' + failingGrades.length + ' times.';
            }

            //revaling
            return {
                getAverage: getAverage,
                getGradeStatus: getGradeStatus,
                getAge: getAge,
                growOlder: growOlder
            };

        })();
var student1 = new Student("shahzad");
var student2 = new Student("ali");
student1.name		//returns "shahzad"
student1.getAge();	//returns 25
student1.growOlder();	//increment age 
student1.getAge();	//returns 26
student1.getAverage();	//returns 70.33333333333333
student1.getGradeStatus();	//returns "You failed 2 times."
student2.name			//returns "ali"
student2.getAge();		//returns 26
student2.getAverage();		//returns 70.33333333333333
student2.getGradeStatus()	//returns "You failed 2 times."

If we want private data to be shared across all instances, we can use a hybrid approach that looks like the module pattern but uses a constructor;

var Student = (function() {
    //everyone shares the same age
    var age = 20;   
    function IStudent(name){
        this.name = name;
    }
    
    IStudent.prototype.getAge = function() {
        return age;
    };
    
    IStudent.prototype.growOlder = function() {
        age++;
    };
    
    return IStudent;
}());

var student1 = new Student("shahzad");
var student2 = new Student("ali");
console.log(student1.name);	//returns shahzad
console.log(student1.getAge());		//returns 20
console.log(student2.name);		//returns ali
console.log(student2.getAge());		//returns 20
student1.growOlder();			//increment age
console.log(student1.getAge());		//returns 21
console.log(student2.getAge());		//returns 21

The IStudent constructor is defined inside an IIFE. The variable age is defined outside the constructor but is used for two prototype methods. The IStudent constructor is then returned and becomes the Person constructor in the global scope. All instances of Person end up sharing the age variable, so chaing the value with one instance automatically affects the other instance.

The Mixins Pattern

Mixins are a powerful way to add functionality to objects while avoiding inheritance. A mixin copies properties from one object to another so that the receiving object gains functionality without inheriting from the supplying object. Unlike inheritance, mixins do not allow you to identify where the capabilities came from after the object is created. For this reason, mixins are best used with data properties or small pieces of functionality. Inheritance is still preferable when you want to obtain more functionality and know where that functionality came from.

Scope-safe constructors

Scope-safe constructors are constructors that we can call with or without new to create a new object instance. This pattern takes advantage of the fact that this is an instance of the custom type as soon as the constructor begins to execute, which lets us alter the constructor’s behavior depending on whether or not you used the new operator.

function Person(name) {
    this.name = name;
}
Person.prototype.sayName = function() {
    console.log(this.name);
};
var person1 = Person("shahzad");		//note: missing “new”
console.log(person1 instanceof Person);		//returns false
console.log(typeof person1);			//returns undefined
console.log(name);				//returns shahzad

The name is created as a global variable because the Person constructor is called without new. Since this code is running in nonrestrict mode so leaving out new would not throw an error. The fact that constructor begins with capital letter should be preceded by new. What if we want to allow this use case and have the function work without new. We can implement a pattern like this;

function Person(name) {
    if (this instanceof Person) {
        //called with "new"
    } else {
        //called without new
    }
}

Let’s re-write our constructor logic;

function Person(name) {
    if (this instanceof Person) {
        this.name = name;
    } else {
        return new Person(name);
    }
}
var person1 = Person("shahzad");
console.log(person1 instanceof Person);		//returns true
console.log(typeof person1);			//returns object
console.log(person1.name);			//returns shahzad

The constructor is called recursively via new if new keyword is not used to create a proper instance of the object. This way following are equivalent;

var person1 = new Person(“shahzad”);
var person2 = Person(“shahzad”);

console.log(person1 instanceof Person);		//returns true
console.log(person2 instanceof Person);		//returns true

Creating new objects without using the new operator is becoming more common. JavaScript itself has several reference types with scope-sfe constructors, such as Object, Array, RegExp, and Error.

Resources

https://www.theodinproject.com/paths/full-stack-javascript/courses/javascript/lessons/factory-functions-and-the-module-pattern

FavoriteLoadingAdd to favorites
Spread the love

Author: Shahzad Khan

Software developer / Architect