JavaScript private members private and public member difference

Source: Internet
Author: User
Tags constructor


Private
Private members are generated by constructors. The normal var variable and the constructor parameters are called private members.

The code is as follows Copy Code
function Container (param) {
This.member = param;
var secret = 3;
var that = this;
}

The constructor creates 3 private instance variables: Param,secret and that. They are added to the object, but cannot be accessed externally, nor can they be the object's own
Public method Access. They can only be accessed by private methods. The private method is the internal method of a constructor.


Public
The members of the object are public members. Any object can be accessed, modified, deleted, or added to a new member. There are two main ways to place members in a new object:

In the constructor
This technique is commonly used to initialize public instance variables. The "This" variable of the constructor is used to add members to the object.

  code is as follows copy code

Functin Container (param) {
    this.member = param;
}
Functin Container (param) {
    this.member = param;
}

//re-encapsulate Document Object
var console={
Write:function (msg) {alert (msg);
};
//person Object
var person={
_name: "Zzl",//static public
_age:28,
Printinfo:function () {Console.Write ( "Name: +person._name+", Age: "+this._age";} Public method, this represents the person
};

//People type (object)
Var people= (function ()
{
var _name= "Zzl";//private
var _age=28;
Return {//public
Printinfo:function () {console.write (' name: ' +_name+ ', Age: ' +_age ');
}
}
());

Person.printinfo ()///Method in Object
People.printinfo ()//Method object exposed child method
Console.Write (person._name);//Properties in Object

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.