Many times we write classes like this and then use new to create objects.
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
function Person(name,age){
//The condition is changed to (this== window) or (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 additions compared to the top way of writing classes.
if(!this.setName){
return new Person(name,age);
}
Okay, the way to create an instance (object) of the class has also become as follows
var p = Person('jack',25);
This way of creation ( Function call) is less "new_", new and spaces than the above one. It is actually new inside the class. This method can reduce 4 bytes each time an object is created.
If the if judgment condition inside the class is replaced by a non-prototype attribute, such as this.name. The program will prompt an error: too much recursion
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);