What is a pattern
I was preparing for the final exam a while ago, but it was a painstaking person and I was really busy. I had no time to update the article. Today I will tell you about the design patterns in JavaScript.
First of all, what we need to know is that pattern is a reusable solution, while anti-pattern is a bad solution to a certain problem.
Common examples of anti-patterns of js
1. Pass strings to setTimeout and setInterval, not functions, which triggers internal use of eval().
2. Define a large number of variables in the global context to pollute the global namespace
3. Modify the prototype of the Object class
4. Use js inline, and js code embedded in HTML files cannot be included in external unit testing tools.
5. Abuse document.write. If you execute document.write after the page is loaded, it will rewrite the page we are in. If you can use document.creatElement instead, try not to use document.write.
Category of design patterns
Creating a Design Pattern
Creative design patterns focus on handling object creation mechanisms to create objects in a way that suits a given situation. Attributes that fall into this category include:
Constructor constructor, Factory factory, Abstract abstraction, Prototype prototype, Singleton singleton and Builder generator
Structural design pattern
Structural patterns are related to object combinations and can often be used to find simple ways to establish relationships between different objects.
Patterns that fall into this category include:
Decorator Decorator, Facade Appearance, Flyweight Encyclopedia, Adapter Adapter and Proxy Proxy
Behavior design pattern
Behavior patterns focus on improving or simplifying communication between different objects in the system.
Behavior patterns include:
Iterator iterator, Mediator mediator, Observer observer, and Visitor visitor
Factory mode
To solve the problem of multiple similar object declarations, we can use a method called factory pattern, which is to solve the problem of instantiating objects with a large number of duplications.
The code copy is as follows:
<script type="text/javascript">
function createObject(name,age,profession){//Central instantiated function {//
var obj = new Object();
obj.name = name;
obj.age = age;
obj.profession = profession;
obj.move = function () {
return this.name + ' at ' + this.age + ' engaged in ' + this.profession;
};
return obj;
}
var test1 = createObject('trigkit4',22,'programmer');//First instance
var test2 = createObject('mike',25,'engineer');//The second instance
alert(test1.move());
alert(test2.move());
</script>
Category of factory model
The factory pattern is divided into simple factories, abstract factories and smart factories. The factory pattern requires the use of a constructor without displaying it.
Simple factory pattern: Use a class (usually a monomer) to generate an instance.
Complex factory pattern: Use subclasses to determine which specific class instance a member variable should be.
The benefits of factory model
The main advantage is that it can eliminate coupling between objects by using engineering methods instead of new keywords. Concentrate all instantiated code in one place to prevent code duplication.
Disadvantages of the factory model
Most classes are best used with new keywords and constructors, which can make the code easier to read. Instead of checking the factory method to know.
The factory pattern solves the problem of repeated instantiation, but there is another problem, that is, identifying the problem, because it is impossible to figure out which instance of the object they are.
The code copy is as follows:
alert(typeof test1); //Object
alert(test1 instanceof Object); //true
When to use factory mode?
Factory mode is mainly used in the following scenarios:
1.When an object or component involves high complexity
2. When it is necessary to easily generate different instances of objects according to the different environments in which they are located
3.When dealing with many small objects or components that share the same attributes
Constructor mode
In ECMAScript, constructors (constructors) can be used to create specific objects. This mode can just solve the problem that the above factory mode cannot recognize object instances.
The code copy is as follows:
<script type="text/javascript">
function Car(model,year,miles){//Constructor mode
this.model = model;
this.year = year;
this.miles = miles;
this.run = function () {
return this.model + " has done " + this.miles + "miles";
}
}
var Benz = new Car('Benz',2014,20000);
var BMW = new Car("BMW",2013,12000);
alert(Benz instanceof Car); //I clearly identify it as subordinate to Car, true
console.log(Benz.run());
console.log(BMW.run());
</script>
Using the constructor method solves the problem of repeated instantiation and the problem of object recognition. The difference between this pattern and the factory pattern is:
1. Create object (new Object()) that is not displayed by the constructor method;
2. Directly assign attributes and methods to this object;
3. No return statement.
There are some specifications for constructor methods:
1. The function name and the instantiated constructor are the same and capitalized (PS: not mandatory, but writing this helps distinguish between constructors and ordinary functions);
2. To create an object through a constructor, the new operator must be used.
Since an object can be created through a constructor, where did this object come from and where did new Object() be executed? The execution process is as follows:
1. When the constructor is used and the new constructor() is used, then the new Object() is executed in the background;
2. Scope the constructor to a new object (that is, the object created by new Object()), and this in the function body represents the object produced by new Object().
3. Execute the code within the constructor;
4. Return the new object (return directly in the background).
Constructor with prototype (constructor)
There is a property called prototype in js. After calling the js constructor to create an object, the new object will have all the properties of the constructor prototype. In this way, multiple Car objects can be created and the same prototype can be accessed.
The code copy is as follows:
<script type="text/javascript">
function Car(model,year,miles) {
this.model = model;
this.year = year;
this.miles = miles;
}
Car.prototype.run = function () {
return this.model + " has done " + this.miles + " miles ";
};
var Benz = new Car('S350',2010,20000);
var Ford = new Car('Ford',2012,12000);
console.log(Benz.run());//"S350 has done 20000 miles"
console.log(Ford.run());
</script>
Now a single instance of run() can be shared among all Car objects.