In most cases, we write classes like this and then use new to create objects.
CopyCode The 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 thisCopy 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 codeCode: var P = person ('jack', 25 );
This creation method (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 change the if judgment condition inside the class to a property on a non-prototype, for example, this. Name. Program prompts an error: too much recursion copy Code the code is as follows: function person (name, age) {
If (! This. name) {
return new person (name, age);
}< br> This. name = Name;
This. age = age;
}< br> person. prototype = {
setname: function (n) {This. name = n ;},
getname: function () {return this. name ;}< BR >}< br> var P = person ('jack', 25);