Use hidden new to create object _ jquery

Source: Internet
Author: User
JQuery. Event class found in JQ. The author is estimated to reduce the amount of code. Defines a class, but does not use the new keyword to create this class object. Instead, you can use method call () to create this object. In most cases, we write classes like this and then use new to create objects.

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 this

The 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:

The 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:

The 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

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.