JavaScript creates private members and static private members

Source: Internet
Author: User

Private Methods and properties

In JavaScript, because there is no concept of classes, you can only simulate classes by using constructors, assuming that you now need to write a phone class that needs to pass in a phone number and then call. The simplest way is to

varfunction(num){  //手机号  this.num= num;  //打电话  thisfunction(phone){      console.log(this"正在呼叫" + phone.num);  }}varnew Phone("13012341234");

For the correctness of the data, we may also check the legality of NUM when assigning it, such as

varPhone= function(num){  if(! This. Checknum (num)) {Throw New Error("mobile phone number is illegal!" "); }//Mobile phone number   This. num= num;//Call   This. Call = function(phone){Console.log ( This. Num +"Calling"+ Phone.num); }}//Verify mobile phone number legalityPhone.prototype.checkNum = function(num){  if(/^1[358]\d{9}$/. Test (num)) {return true; }Else{return false; }}varP1 =NewPhone ("13312341234");varP2 =NewPhone ("15812341234");p 1.call (p2);//13312341234 is calling 15812341234 .

This can be a lot better, but although NUM is controlled when the object is created, when this code is used by other programmers, he may assign values directly to the phone, such as

p1.num"abcdefg";p1.call(p2);

Even though we can verify the integrity of the data in the constructor, but we still cannot control the property being arbitrarily modified, in this case, we can use the closed package to change num to private variable, the outside world wants to access NUM only through its get and set method.

varPhone= function(num){  //Private variable  var_num;//Privileged Methods   This. Setnum = function(num){    if(! This. Checknum (num)) {Throw New Error("mobile phone number is illegal!" ");  } _num = num; }; This. Getnum = function(){    return_num; }; This. Call = function(phone){Console.log (_num +"Calling"+ Phone.getnum ()); };//Initialize   This. Setnum (num);} Phone.prototype.checkNum = function(num){  if(/^1[358]\d{9}$/. Test (num)) {return true; }Else{return false; }}varP1 =NewPhone ("13312341234");varP2 =NewPhone ("15812341234");p 1.call (p2);//13312341234 is calling 15812341234 .

A property or method such as NUM is declared with the Var keyword, not this, which means it can only be used inside the function, thus forming a private property, which is similar to a private method in which a function is declared directly in the constructor. Private methods cannot be accessed directly externally, but can be accessed through a closure feature such as Setnum and Getnum, a public method that accesses a private property called a privileged method.
However, it is also a disadvantage to create objects in this way, the call function calls the private property num, so it can only be placed inside the constructor, and too many privileged methods tend to consume too much memory, because each generation of a new object instance will generate a copy for each private method and privileged method. This also consumes more memory than the first way.

Static Methods and properties

Static members are related to a class, not to an instance, which means that static members are accessed directly through the class, and all instances share a static member, and it is simple to implement a common static method by assigning it to a constructor, such as a Phone.count = 5; private static member that cannot be directly accessed externally. This will require a closure:

varPhone= ( function(){  //Static private property  varCount =0;return  function(num){    //Private variable    var_num;//Privileged Methods     This. Setnum = function(num){      if(! This. Checknum (num)) {Throw New Error("mobile phone number is illegal!" ");    } _num = num; }; This. Getnum = function(){      return_num; }; This. Call = function(phone){Console.log (_num +"Calling"+ Phone.getnum ()); };//Over 50 phones not createdcount++;if(Count > -){Throw New Error("Only 50 phones can be created!" "); }//Initialize     This. Setnum (num); }}) () Phone.prototype.checkNum = function(num){  if(/^1[358]\d{9}$/. Test (num)) {return true; }Else{return false; }}varP1 =NewPhone ("13312341234");varP2 =NewPhone ("15812341234");p 1.call (p2);//13312341234 is calling 15812341234 .

Basically similar to the way it was created, but here the constructor becomes an inline function, which is returned by an immediate execution of the external function, which makes the count of the external function accessible to the constructor, because the external function is only loaded once, so count has only one, and when the 50 instances are created, Count is assigned to 50 and will be an error if you continue to create.

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

JavaScript creates private members and static private members

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.