Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.
JavaScript itself is a high degree of freedom of language, process programming, object-oriented programming can be developed according to their own mind, the essence of a process programming language, but if the introduction of appropriate libraries or their own definition of some tools and functions, complete can achieve an object-oriented into the development way.
Here’s a quick comparison of several ways to create objects.
The factory pattern
As the name implies, the comparison of a kind of solidified way, but win in simple and light
function createPerson(name){
var o = new Object()
o.name = name;
o.getName = function(){
console.log(this.name)
}
return o
}
var person = createPerson('kevin')
Copy the code
Disadvantages: Objects are unrecognizable, pointing to a prototype
Constructor pattern
Can be equivalent to a parent class in ES6
function Person(name){
this.name = name;
this.getName = function(){
console.log(this.name)
}
}
var person1 = new Person('kevin')
Copy the code
Advantages: Instances can be identified as a specific type
Disadvantages: Each method is created every time an instance is created
Constructor pattern optimization
function Person(name){
this.name = name;
this.getName = getName
}
function getName(){
console.log(this.name)
}
var person1 = new Person('kevin')
Copy the code
Advantage: Solves the problem that every method has to be recreated
Cons: Defeats the purpose of encapsulation
The prototype pattern
function Person(name){}
Person.prototype = {
constructor: Person,
name: 'kevin',
getName: function(){
console.log(this.name)
}
}
var person1 = new Person()
Copy the code
Advantages: The owning constructor can be found using the constructor property
Disadvantages: 1. All attributes and methods are shared; 2. Parameters cannot be initialized
Composite pattern (constructor pattern + stereotype pattern)
function Person(name){
this.name = name;
}
Person.prototype = {
constructor: Person,
getName: function(){
console.log(this.name);
}
}
var person1 = new Person()
Copy the code
Advantages: Sharing of the shared, private of the private, the most widely used way
Disadvantages: Write separately, not best encapsulated