Use hidden new to create an object

Source: Internet
Author: User

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

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.