First: Factory mode: Code as follows
Cons: objects are not recognized because the prototypes point to (object)
function Person (name) { varnew Object (); = name; function () { returnthis. Name; } return obj}
var person = person ("Ayden") Console.log (person.name)//Ayden Console.log (Person.say ())// I am ayden
Second: Constructor pattern: Code as follows
Advantage: An instance can be identified as a specific type, which can be divided into ' classes '
Cons: Each method is created once each time the instance is created
function Person (name) { this. Name = name; This function () { returnthis. Name; }} var New Person ("Ayden") console.log (person)
Construction Mode Optimization: The code is as follows
Pros: Resolves an issue where "every method is created once every time the instance is created"
Disadvantage: One of the three main characteristics of object-oriented encapsulation. What is it called encapsulation?
function Person (name) { this. Name = name; this. Say = say}function say () { returnthis. Name;} var New Person ("Ayden") console.log (person)
Third: Prototype mode: Code as follows
Advantage: The method of the instance is not re-created
Cons: 1. All properties and methods are shared 2. Parameter 3 cannot be initialized. Always want to write the code together, that is, the package
function Person () { = ' Ayden 'function () { returnthis. Name}varnew person (); Console.log (person)
Prototype Mode optimization: The code is as follows
Advantages: Better Encapsulation
Cons: Missing the constructor attribute
function= { name:"Ayden", say:function () { Returnthis. Name } {varnew person ()
Prototype mode re-optimization:
Pros: Instances can find the owning constructor through the constructor property
Cons: 1. All properties and methods are shared 2. Parameter cannot be initialized
function= { Constructor:person, "Ayden", function () { return This . Name }} var New Person ()
IV: Mixed mode: The code is as follows:
Pros: The private private, shared share (the most widely used way)
Cons: Hopefully all written together, i.e. better encapsulation
function Person (name) { this. Name = name; } = { say:function () { returnthis. Name } } var New Person ("Ayden"); var New Person ("Tom")
JS create objects in several ways