The factory pattern

function createPerson(name, age){
    let o = new Object()
    o.name = name
    o.age = age
    o.sayName = function(){
		console.log(this.name)
    }
}
let person1 = createPerson('Rick'.18)
Copy the code

The createPerson() function takes three arguments from which to build an object containing the Person information. This function can be called multiple times with different arguments, each time returning an object with three properties and one method.

While this factory pattern solves the problem of creating multiple similar objects, it does not solve the problem of object identification (that is, what type of newly created objects are)

Constructor pattern

function Person(name, age){
    this.name = name
    this.age = age
    this.sayName = function(){
        console.log(this.name)
    }
}

let person1 = new Person('Rick'.12)
Copy the code

To create an instance of Person, use the new operator. Calling the constructor in this way does the following.

  1. Creates a new object in memory.

  2. The [[Prototype]] property inside the new object is assigned to the constructor’s Prototype property.

  3. The this inside the constructor is assigned to the new object (i.e. this refers to the new object).

  4. Executes the code inside the constructor (adding properties to the new object).

  5. If the constructor returns a non-empty object, the object is returned; Otherwise, the newly created object is returned.

Question:

The same function is created repeatedly, as sayname in the example above

The prototype pattern

Each function creates a Prototype property, which is an object containing properties and methods that should be shared by instances of a particular reference type. In effect, this object is the prototype of the object created by calling the constructor.

The advantage of using a prototype object is that the properties and methods defined on it can be shared by the object instance. Values that were assigned directly to object instances in the constructor can be assigned directly to their prototypes.

function Person(){
    Person.prototype.name = 'Rick'
    Person.prototype.age = 12
    Person.prototype.sayName = function(){
        console.log(this.name)
    }
}
let person1 = new Person()
let person2 = new Person()
person1.sayName() // Rick
person2.sayName() // Rick
 
console.log(person1.sayName === person2.sayName) // true
Copy the code