Created by constructors and similar to factory-based creation, the biggest difference is that the name of the function is the name of the class, and the first letter is capitalized according to the Java conventions.
When you create an object using a constructor, The definition of the property is done inside the function through the This keyword .
functionPerson (name, age) { This. Name =name; This. Age =Age ; //the problem is that all objects will allocate space for the behavior This. Say =function(){//Note: Say is also a property of personAlert This. Name + "--" + This. Age); }}//creating objects with new personvarP1 =NewPerson ("Leon", 22);varP2 =NewPerson ("Ada", 32);p 1.say (); P2.say (); Alert (typeofp1);//Object//you can use constructors to detect the type of an object in the following waysAlert (P1instanceofperson);//trueAlert (P1.say = = P2.say);//false because the method is defined in the class, all two say are not the same
The first problem with creating a constructor is that each object will have a copy of the method, and if the object has many methods, the space occupancy will be greatly increased .
How to improve? A function can be defined in a global variable so that the behavior/method in the class points to the same function.
functionPerson (name, age) { This. Name =name; This. Age =Age ; This. Say =say;}functionsay () {alert ( This. Name + "--" + This. age);}varP1 =NewPerson ("Leon", 22);varP2 =NewPerson ("Ada", 32);p 1.say (); P2.say (); Alert (P1instanceofperson);//trueAlert (P1.say = = P2.say);//true
Set the behavior to the global behavior, if all the methods are designed as global functions, this function can be called by the window , this time it destroys the encapsulation of the object,
And if an object has a large number of methods, it will result in a large number of global functions in the entire code, which will not be conducive to development.
Constructor for the creation of JavaScript objects