Analysis of JavaScript writing methods

Source: Internet
Author: User

From this article, we will analyze js oo writing methods from a shortest to a deep one. There will be about 5-8 articles. The writing methods of Popular Libraries (frameworks) will be analyzed later. Writing Methods of some writing tool functions or frameworks are essentiallyConstructor + prototype. Only by understanding this can we truly understand how to use JavaScript to write object-oriented code. Or use object-oriented methods to organize code. Of course, JavaScript can also write functional code, which is generic.

BKJIA recommended topics: JavaScript functional programming

For the sake of singularity, class inheritance, (private, protected) attributes or methods are not considered for the moment. EMCAScript does not actually have the concept of class, but can be understood as a more general concept.

1. constructor Method

 
 
  1. /** 
  2. * Person class: defines a Person with a property name and a getName method. 
  3. * @ Param {String} name 
  4. */ 
  5. FunctionPerson (name ){
  6. This. Name = name;
  7. This. GetName =Function(){
  8. Return This. Name;
  9. }
  10. }

This style makes Java a little more friendly because some parameters need to be configured to construct an object, and the parameters need to be assigned to this in the class. But the difference with Java is that JS uses function to replace class, and the parameter does not need to define the type.

After the class is written, we create several objects:

 
 
  1. var p1 = new Person("Jack");  
  2. var p2 = new Person("Tom");  
  3. console.log(p1 instanceof Person);//true  
  4. console.log(p2 instanceof Person);//true 

The console output also proves that p1 and p2 are indeed object instances of the Person class.

The advantage of this method is that different object instances can be constructed based on parameters. The disadvantage is that each instance object will generate the getName method version during the construction, resulting in a waste of memory.

Experienced programmers use an external function to replace Class methods, so that each object shares the same method. The modified class is as follows:

 
 
  1. // External functions 
  2. FunctionGetName (){
  3. Return This. Name;
  4. }
  5. FunctionPerson (name ){
  6. This. Name = name;
  7. This. GetName = getName;// Note the following: 
  8. }

Some people may think that the Code style is a little unsatisfactory, and it is not as compact as Java. But it can indeed reduce memory consumption.

2. Prototype

 
 
  1. /** 
  2. * Person class: defines a Person with a property name and a getName method. 
  3. */ 
  4. FunctionPerson (){}
  5. Person. prototype. name ="Jack";
  6. Person. prototype. getName =Function(){Return This. Name ;}

Link all attributes (fields) and methods of the class to prototype.

Create several objects for testing

 
 
  1. var p1 = new Person();  
  2. var p2 = new Person();  
  3. console.log(p1.getName());//jack  
  4. console.log(p2.getName());//jack 

It can be seen that the output is jack. The disadvantage of the prototype is that the object instance cannot be constructed through parameters (generally, the attributes of each object are different ), the advantage is that all object instances share the getName method (relative to the constructor method) without causing memory waste.

3. constructor + prototype

Take the advantages of the first two methods:

A. Use constructors to define class attributes (fields ).

B. Define the class method in prototype mode.

 
 
  1. /** 
  2. * Person class: defines a Person with a property name and a getName method. 
  3. * @ Param {String} name 
  4. */ 
  5. FunctionPerson (name ){
  6. This. Name = name;
  7. }
  8. Person. prototype. getName =Function(){
  9. Return This. Name;
  10. }

In this way, you can use the constructor to construct people with different names. The object instances also share the getName method, without causing a waste of memory.

However, it seems that this code style is still not as compact as Java classes. The attributes, constructor methods (functions), and methods are enclosed in braces.

 
 
  1. Public ClassPerson {
  2. // Attribute field) 
  3. String name;
  4. // Constructor) 
  5. Person (String name ){
  6. This. Name = name;
  7. }
  8. // Method 
  9. String getName (){
  10. Return This. Name;
  11. }
  12. }

To make JS Code more compact, move the method code hanging in prototype to the braces of function Person.

 
 
  1. function Person(name) {  
  2.     this.name = name;  
  3.     Person.prototype.getName = function() {  
  4.         return this.name;  
  5.     }  

It seems amazing. You can write it like that! Verify

 
 
  1. var p1 = new Person("Jack");  
  2. var p2 = new Person("Tom");  
  3. console.log(p1.getName());//Jack  
  4. console.log(p2.getName());//Tom 

No error is reported, and the console outputs it correctly. It seems perfect to write like this.

A. You can create an object instance by passing parameters.

B. object instances share the same method without causing memory waste.

C. Compact code style

But every time a new object is created

 
 
  1. Person.prototype.getName = function() {  
  2.         return this.name;  

This causes unnecessary repeated operations. Because the getName method only needs to be executed once on prototype. You only need to make some changes.

 
 
  1. FunctionPerson (name ){
  2. This. Name = name;
  3. If(Person. _ init = undefined ){
  4. Alert ("I only execute once! ");
  5. Person. prototype. getName =Function(){
  6. Return This. Name;
  7. }
  8. Person. _ init = 1;
  9. }
  10. }

Two new objects

 
 
  1. VarP1 =NewPerson ("Andy");// The First Time "new" will pop up, "I only execute once! ' 
  2. VarP2 =NewPerson ("Lily");// The new object will not be executed in the future 

Link: http://www.cnblogs.com/snandy/archive/2011/03/06/1971764.html

  1. How to Write high-quality Javascript code
  2. Detect Android devices using JavaScript or PHP
  3. A deep understanding of the closure features of JavaScript
  4. New JavaScript code optimization tool UglifyJS
  5. JavaScript cross-origin summary and Solutions

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.