How JavaScript Creates objects

Source: Internet
Author: User

This article mainly refers to Nanyi's Javascript object-oriented programming (a): encapsulation

1. Original method (also the simplest method)

1 var p1 = {}; 2 var New Object ();

The two lines of code above have the same effect.

1 var p1 = {}; 2 p1.name = ' Zhang San '; 3 p1.age =; 4 5 var p2 = {}; 6 p2.name = ' cui Hua '; 7 p2.age = 18;

2. Original method Upgrade version

1 function Person (name, age) {2     return {3        name:name,4        age:age5    }   6}7var p1 = person (' Zhang San ',%); 8 var p2 = person (' Cui Hua ', 18);

The object created by this method has no connection, its nature and Method 1 are no different.

3. Constructor mode (use this)

1 function Person (name, age) {2     this. Name = name; 3     this. Age = Age ; 4 }5varnew person (' Zhang San ', +); 6 var New Person (' Cui Hua ', 18);

The constructor property of the preceding code instance points to their constructor.

1 // true 2 // true 3 4 instanceof // true 5 instanceof // true

and verify with instanceof that it is indeed an instance of person.

Problems with the construction method

1 functionPerson (name, age) {2      This. Name =name;3      This. Age =Age ;4      This. Takebus =function() {5Alert (' Take a bus. '));6     }7 }8 varP1 =NewPerson (' Zhang San ', 23);9 varP2 =NewPerson (' Cui Hua ', 18);

After adding a "Takebus" method to the above method, the surface looks fine, but:

1 // false

P1 and P2 respectively have a "Takebus" this method, that is, "Takebus" This method is not common. Cause waste of resources. So how is it common?

4. Prototype mode

1 functionPerson (name, age) {2      This. Name =name;3      This. Age =Age ;4 }5 6Person.prototype.takeBus =function() {7Alert (' Take a bus. '));8 }9         Ten varP1 =NewPerson (' Zhang San ', 23); One varP2 =NewPerson (' Cui Hua ', 18); A  -P1.takebus = = P2.takebus//true

You can see that using prototype this way, the object "Takebus" method that "person" instantiates gets is the same method.

How JavaScript Creates objects

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.