Home >Web Front-end >JS Tutorial >Use hidden new to create objects_jquery

Use hidden new to create objects_jquery

WBOY
WBOYOriginal
2016-05-16 18:08:521203browse

Many times we write classes like this and then use new to create objects.

Copy code 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);

Change to this
Copy code The code is as follows:

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.
Copy code The code is as follows:

if(!this.setName){
return new Person(name,age);
}

Okay, the way to create an instance (object) of the class has also become as follows
Copy code The code is 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
Copy code The 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);
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn