In most cases, we write classes like this and then use new to create objects.
Copy codeThe Code is as follows:
Function Person (name, age ){
This. name = name;
This. age = age;
}
Person. prototype = {
SetName: function (n) {this. name = n ;},
GetName: function () {return this. name ;}
}
Var p = new Person ('jack', 25 );
Changed to this
Copy codeThe Code is as follows:
Function Person (name, age ){
// Change the condition to (this = window), (this = self), or (this. constructor! = Object)
If (! This. setName ){
Return new Person (name, age );
}
This. name = name;
This. age = age;
}
Person. prototype = {
SetName: function (n) {this. name = n ;},
GetName: function () {return this. name ;}
}
Var p = Person ('jack', 25 );
Note that this class has the following more than the top write class method:
Copy codeThe Code is as follows:
If (! This. setName ){
Return new Person (name, age );
}
Well, the method for creating an instance (object) of the class is also changed to the following:
Copy codeThe Code is as follows:
Var p = Person ('jack', 25 );
This method of creation (function call) is less "new _", "new", and "space" than above, and is actually new in the class. In this way, you can reduce the number of bytes each time you create an object.
If you replace the if condition in the class with an attribute on a non-prototype, for example, this. name. The program prompts an error: too much recursion
Copy codeThe Code is as follows:
Function Person (name, age ){
If (! This. name ){
Return new Person (name, age );
}
This. name = name;
This. age = age;
}
Person. prototype = {
SetName: function (n) {this. name = n ;},
GetName: function () {return this. name ;}
}
Var p = Person ('jack', 25 );