SoFunction
Updated on 2025-03-04

Definition and usage example analysis of constructor mode (generator mode) in JavaScript design pattern

This article describes the definition and usage of the constructor mode (generator mode) of JavaScript design pattern. Share it for your reference, as follows:

Although the factory pattern solves the problem of repeated instantiation, the object type cannot be recognized.

A constructor (constructor method) can be used to create specific objects, which can solve the problem that the factory pattern cannot recognize object instances. In other words, using the constructor method solves the problem of repeated instantiation and also solves the problem of object recognition.

The difference between the constructor mode and the factory mode is:

① Create object that is not displayed by the constructor method(new Object())

② Directly assign attributes and methods tothisobject;

③ NoreturnStatement.

Specifications for constructor methods:

① The function name and the instantiated constructor are the same and capitalized (not mandatory, but help to distinguish between constructors and ordinary functions);

② Create an object through a constructor, you must usenewoperator.

function Person(name, age) {
   = name;
     = age;
   = function() {
      alert();
    };
}
var person1 = new Person("Alice", 23);
var person2 = new Person("Bruce", 22);

Constructor mode problem:Each method must be recreated on each instance.

reason:Functions in JavaScript are objects. Each function is defined, and one is instantiated.FuntionObject, so each instance created with the constructor has a method with the same name, but these methods are not the sameFunctionInstances of , because functions of the same name on different instances are not equal.

solve:For prototype mode, see:///article/

For more information about JavaScript, please view the special topic of this site: "JavaScript object-oriented tutorial》、《Summary of JavaScript switching effects and techniques》、《Summary of JavaScript search algorithm skills》、《Summary of JavaScript Errors and Debugging Skills》、《Summary of JavaScript data structure and algorithm techniques》、《JavaScript traversal algorithm and skills summary"and"Summary of JavaScript mathematical operations usage

I hope this article will be helpful to everyone's JavaScript programming.