Multiple ways to create objects in JS Red Book

Borrowing from the notes of the big guys in github, it made me feel much smoother when reading the Red Book. Address: https://github.com/mqyqingfeng/Blog

Although the Object constructor or object literal can be used to create a single object, using the same interface to create many objects will generate a lot of repetitive code.

6.2.1 Factory Mode

function createPerson (name,age){
    
    
    var o = new Object();
    o.name = name;
    o.age = age;
    o.getName = function() {
    
    
        console.log(this.name)
    }
    return o;
}
var person1 = createPerson("Pinocchio",14)

Although he solved the problem of creating many similar objects, he did not solve the problem of object recognition because all instances point to a prototype.

6.2.2 Constructor Mode

function Person(name,age){
    
    
    this.name = name;
    this.age = age;
    this.getName = function(){
    
    console.log(this.name);}
}
var person1 = new Person("Pinocchio",14)

**Pros: **Each instance can be identified as a specific type. Disadvantage : Every time an instance is created, each method has to be created once.

This method will go through the following four steps:

  • Create a new object in the heap memory
  • Assign the scope of the constructor to the new object (so this points to this new object)
  • Execute the code in the constructor (add properties to this new object)
  • Use the newly created object as the return value

alert(person1 instanceof Object); //true All objects are Object instances, and person1 is also an instance of Person

6.2.3 Optimization of Constructor Mode

function Person(name,age){
    
    
    this.name = name;
    this.age = age;
    this.getName = getName
}
function getName(){
    
    
    console.log(this.name)
}
var person1 = new Person("Pinocchio",14)

**Advantages:** Solve the problem that every method has to be recreated. **Disadvantages:** This has no encapsulation effect. Other people can also use the getName function.

6.2.4 Prototype mode

Every function has a prototype property, which is a pointer to an object.

function Person(){
    
    
    Person.prototype.name = "Pinocchio";
    Person.prototype.age = 14;
    Person.prototype.getName = function(){
    
    console.log(this.name);}
}
var person1 = new Person();
var person2 = new Person();
alert(person1.getName == person2.getName);   //true

**Pros:** The method will not be recreated. **Disadvantages:** All properties and methods are shared, and parameters cannot be initialized. For example, if there is a reference type in the prototype, then the change of one instance attribute will cause another instance attribute to also change.

6.2.5 Combination Mode: Use Constructor + Prototype Mode

The constructor mode is used to define instance properties, and the prototype mode is used to define methods and shared properties.

function Person(name,age){
    
    
    this.name = name;
    this.age = age;
    this.friends = ['li','wang'];
}
Person.prototype = {
    
    
    constructor:Person;
    sayName(){
    
    
        alert(this.name)
    }
}
var person1 = new Person('dsa',23)

**Advantages: **The shared sharing, the private private, the most widely used method.

** Disadvantages: ** Not written together, that is, better encapsulation

6.2.6 Dynamic Prototype Mode

function Person(name,age){
    
    
	this.name = name;
    this.age = age;
    if(typeof this.sayName != "function"){
    
    
        Person.prototype.sayName = function(){
    
    
            alert(this.name)
        }
    }
}
var person1 = new Person('dsa',14)

**Advantages:** Better encapsulate the combination mode.

The above judgment with if is to prevent Person.prototype.sayName=function(){} from being called every time new Person().

Add an if judgment, only in the first new Person(), construct the sayName function once. When new Person() is used for the second time, since the sayName function is already on the prototype chain, typeof this.sayName is equal to'function', so there is no need to build the sayName function.

6.2.7 Parasitic Constructor Pattern

A method of parasitic in the constructor.

function SpecialArray(){
    
    
    var values = new Array();
    values.push(...arguments);
    values.toPipedString = function(){
    
    
        return this.join('|')
    }
}
var colors = new SpecialArray('red','blue','green')

This method can be used in special circumstances. For example, if we want to create a special array with additional methods but don't want to modify the Array constructor directly, we can write it like this.

But this newis not the relationship between the properties of the prototype object out of the constructor or a constructor.

6.2.8 Safe Constructor Mode

function person(name){
    
    
    var o = new Object();
    o.sayName = function(){
    
    
        console.log(name);
    };
    return o;
}
var person1 = person('kevin');
person1.sayName(); // kevin
person1.name = "daisy";
person1.sayName(); // kevin
console.log(person1.name); // daisy

The so-called safe object refers to an object that has no public properties and its methods do not refer to this.

Guess you like

Origin blog.csdn.net/Pinoochio/article/details/113706671