Use constructors to define class attributes (fields) and use prototype to define class methods. There is a third method. This method seems to be widely used by many people. Take the advantages of the first two methods:
A. Use constructors to define class attributes (fields)
B. Define the class method in prototype mode.
There is a third method. This method seems to be widely used by many people.
3. Integrated constructor/prototype
The Code is as follows:
/**
* Person class: defines a Person with a property name and a getName method.
* @ Param {String} name
*/
Function Person (name ){
This. name = name;
}
Person. prototype. getName = function (){
Return this. name;
}
In this way, you can use the constructor to construct people with different names. The object instances also share the getName method, without causing a waste of memory.
However, it seems that this code style is still not as compact as java classes. The attributes, constructor methods (functions), and methods are enclosed in braces.
The Code is as follows:
Public class Person {
// Attribute (field)
String name;
// Constructor (function)
Person (String name ){
This. name = name;
}
// Method
String getName (){
Return this. name;
}
}
To make js Code more compact, move the method code hanging in prototype to the braces of function Person.
The Code is as follows:
Function Person (name ){
This. name = name;
Person. prototype. getName = function (){
Return this. name;
}
}
It seems amazing. You can write it like that! Verify
The Code is as follows:
Var p1 = new Person ("Jack ");
Var p2 = new Person ("Tom ");
Console. log (p1.getName (); // Jack
Console. log (p2.getName (); // Tom
No error is reported, and the console outputs it correctly. It can be written like this.
Well, it seems perfect.
A. You can create an object instance by passing parameters.
B. object instances share the same method without causing memory waste.
C. Compact code style
But every time a new object is created
Person. prototype. getName = function (){
Return this. name;
}
This causes unnecessary repeated operations. Because the getName method only needs to be executed once on prototype. Only a slight transformation is required:
The Code is as follows:
Function Person (name ){
This. name = name;
If (Person. _ init = undefined ){
Alert ("I only run once! ");
Person. prototype. getName = function (){
Return this. name;
}
Person. _ init = 1;
}
}
Two new objects,
The Code is as follows:
Var p1 = new Person ("Andy"); // The First Time "new" appears, "I only run once! '
Var p2 = new Person ("Lily"); // The new object will not be executed again later.