There are many methods to implement javascript writing on the Internet. I have summarized the following methods.
Constructor method; prototype; constructor method + prototype hybrid mode
Now let's take a look at the advantages and disadvantages of the above methods:
ConstructorMethod
This is the most basic and most similar way to writing a class in Java. The Code is as follows:
- // Create a Student class
- Function Student (name ){
- This. name = name;
- This. sayName = function (){
- Alert (this. name );
- };
- }
- // New two different Student.
- Var jimmy = new Student ('Jimmy ');
- Var henry = new Student ('henry ');
- Jimmy. sayName (); // display jimmy
- Henry. sayName (); // display henry
This method is simple and clear, and it also fits the appetite of Java er. However, every new object will allocate a sayName method in the memory, and the performance is not very good.
PrototypeMethod
- // Create a Student class
- // Set attributes and methods through Student. prototype
- Function Student (name ){
- Student. prototype = name;
- Student. prototype. sayName = function (){
- Alert (this. name );
- }
- }
- // New two different Student.
- Var jimmy = new Student ('Jimmy ');
- Var henry = new Student ('henry ');
- Jimmy. sayName (); // display henry !!!
- Henry. sayName (); // display henry !!!
Maybe the code executed is different from the expectation of some kids shoes. henry is displayed in both alert! In fact, it is easy to understand. both attributes and methods are set through prototype. the same attribute or method of different objects points to the same memory, so henry is set after jimmy. so henry overwrites jimmy.
HybridMethod
The constructor can allocate different memory for each object of the same class, which is suitable for setting attributes when writing classes, however, when setting the method, we need to share the same memory with different objects in the same class. it is best to use a prototype for writing methods. therefore, when writing a class, you need to mix the constructor and prototype. look at the Code:
- // Create a Student class
- // Set attributes through Constructor
- // Method set through Student. prototype
- Function Student (name ){
- This. name = name;
- Student. prototype. sayName = function (){
- Alert (this. name );
- }
- }
- // New two different Student.
- Var jimmy = new Student ('Jimmy ');
- Var henry = new Student ('henry ');
- Jimmy. sayName (); // display jimmy
- Henry. sayName (); // display henry
So far so good. Different objects of the same class have their own memory and the methods share the same memory. In fact, there is still a small problem:
Every new object is executed once.
- Student.prototype.sayName = function(){
- alert(this.name);
- }
This causes unnecessary repeated operations. You can set a flag bit in the class. During the first execution, set true for this flag bit. If it is true, the prototype method is no longer set.