Amazing JavaScript object-oriented (4)

Source: Internet
Author: User

 

 

This time, let's talk about "static.

 

Static member variable

 

As we all know, static member variables are the variables that only store one copy of the entire class. No matter how many objects you create through this class, all objects share one static member variable. Static variables can be accessed by class names or objects.

 

In JavaScript, such member variables are defined as follows:

 

Testclass. svar =   1 ;

 

However, the variables created in this way only conform to the features of "retaining a copy" and "accessing by class name. In addition, such variables can only be public and cannot be accessed through objects. When the class member method accesses the variable, it still needs to be accessed through the class name. In fact, such a mechanism is only to bind a "father" to the variable, instead of being as rigorous as C ++ or Java.

 

Static member functions

 

Static member functions can be called through class or class objects, and member variables cannot be accessed in the function body.

 

In JavaScript, the definition of such a member method is similar to that of "static member variables:

 

Testclass. smethod =   Function (){};

 

In such a function, you can use this or class name to access "static member variables ".

 

Example

 

Code
< Script Type = " Text/JavaScript " >

// Class Declaration
Function Testclass (){
// Define class members
This . Svar =   10 ;
This . Smethod =   Function (){
Alert ( This . Svar );
}
};

//Define static variables
Testclass. svar= 1;

//Define static methods
Testclass. smethod= Function(){
Alert (This. Svar );
}

//Call static variables and static methods
Alert (testclass. svar );
Testclass. smethod ();

Test= NewTestclass ();
//Call member variables and member Methods
Alert (test. svar );
Test. smethod ();

</SCRIPT>

 

 

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.