Constructor pattern

This is the first day of my participation in the August More Text Challenge. For details, see “August More Text Challenge”.

In object-oriented programming, a constructor is a special function that initializes a newly created object when its memory is allocated. An object constructor is used to create an object of a particular type. First, it is intended to use the object, and then, when the object is first created, the constructor is used to assign values to the properties and methods of the members by receiving parameters.

Base constructor

Inside the constructor, the keyword this refers to the object that was just created.

// The constructor
function Car(model, year, miles) {
  this.model = model;
  this.year = year;
  this.miles = miles;

  this.toString = function () {
    return `The ${this.model} has done The ${this.miles} miles`;
  };
}

const civic = new Car('Honda Civic'.2009.20000);
const mondeo = new Car('Ford Mondeo'.2010.5000);

console.log(civic.toString()); // "Honda Civic has done 20000 miles"
console.log(mondeo.toString()); // "Ford Mondeo has done 5000 miles"
Copy the code

The above is a simple version of the constructor pattern, but it still has some problems. One is that it’s hard to inherit, and the other is that functions like toString() are redefined in every object created by the Car constructor. This is very bad. Ideally, all Car objects should refer to the same function. A constructor that uses a “prototype” has a Prototype property for each function in JavaScript. When we call JavaScript’s constructor to create an object, the properties on constructor Prototype are visible to the object being created. This allows you to create multiple Car instances using the same Prototype method.

// The constructor
function Car(model, year, miles) {
  this.model = model;
  this.year = year;
  this.miles = miles;
}

Car.prototype.toString = function () {
  return `The ${this.model} has done The ${this.miles} miles`;
};

const civic = new Car('Honda Civic'.2009.20000);
const mondeo = new Car('Ford Mondeo'.2010.5000);

console.log(civic.toString()); // "Honda Civic has done 20000 miles"
console.log(mondeo.toString()); // "Ford Mondeo has done 5000 miles"
Copy the code

With the above code, a single toString() instance is shared by all Car objects. Let’s take a look at ES6 class writing.

class Car {
  constructor(model, year, miles) {
    this.model = model;
    this.year = year;
    this.miles = miles;
  }

  toString() {
    return `The ${this.model} has done The ${this.miles} miles`; }}const civic = new Car('Honda Civic'.2009.20000);
const mondeo = new Car('Ford Mondeo'.2010.5000);

console.log(civic.toString()); // "Honda Civic has done 20000 miles"
console.log(mondeo.toString()); // "Ford Mondeo has done 5000 miles"
Copy the code

reference

JavaScript Design Patterns