Most of the time we write classes like this and then use new to create objects.
Copy Code code 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);
Change to this.
Copy Code code as follows:
function Person (name,age) {
The condition is changed to (This==window) or (this==self) or (This.constructor!=object)
if (!this.setname) {
Return to 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 more of the following than the top write class method
Copy Code code as follows:
if (!this.setname) {
Return to new person (name,age);
}
Well, the way you create instances (objects) of a class becomes the following
Copy Code code as follows:
var p = person (' Jack ', 25);
This way of creating (function calls) is less "new_" than the above, new and whitespace, actually new within the class. In this way, you can reduce by 4 byte each time you create an object.
If the inside of the class if the condition is replaced by prototype properties, such as THIS.name. The program prompts for an error: too much recursion
Copy Code code 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);