post's image

Design Pattern in JS Part 1: Simple pattern

Ghost wrote 3 years ago (Nov 23, 2022) with 566👁️ | 2 mins read

Brief some pattern after reading JavaScript Design Pattern

1. Creational Pattern

const newItem = {}; // not really empty, it still has prototype
const newItem2 = Object.create(null); // real empty
const newItem3 = new Object(); // has prototype too

2. Constructor Pattern

  • Without prototype
function Car(model, year, miles) {
    this.model = model;
    this.year = year;
    this.miles = miles;
    this.toString = function () { // every single Car object has store this function separately
        return this.model + " has done " + this.miles + " miles";
    };
}
  • With prototype
function Car(model, year, miles) {
  this.model = model;
  this.year = year;
  this.miles = miles;
}
Car.prototype.toString = function () { // same toString shares between every single instance of Car
  return this.model + " has done " + this.miles + " miles";
};
var civic = new Car("Honda Civic", 2009, 20000);
var mondeo = new Car("Ford Mondeo", 2010, 5000);
console.log(civic.toString());

3. Singleton Pattern

const mySingleton = function () {
    // here are our private methods and variables
    var privateVariable = 'something private';
    function showPrivate() {
        console.log(privateVariable);
    }
    // public variables and methods (which can access // private variables and methods )
    return {
        publicMethod: function () {
            showPrivate();
        },
        publicVar: 'the public can see this!'
    };
};
const single = mySingleton();
single.publicMethod(); // logs 'something private'
console.log(single.publicVar); // logs 'the public can see this!'

4. Factory Pattern

  • Creates objects without specifying the exact class of the object that will be created.
function Car(make, model) {
  this.make = make;
  this.model = model;
}
function CarFactory() {
  return new Car("Toyota", "Camry");
}
const myCar = CarFactory();