JavaScript defines private method descriptions (private methods) _javascript tips

Source: Internet
Author: User
Tags variable scope

Once thought in the JavaScript world, all methods are public, can not really technically define a private method, today again found: I was wrong!

Copy Code code as follows:

var person = function (name,sex) { = name; = sex;
var _privatevariable = "";//Private variable
The method defined in the constructor, that is, a private method
function Privatemethod () {
_privatevariable = "Private Value";
Alert ("Private method is called!") Private member Value: "+ _privatevariable";
Privatemethod (); Private methods can be invoked inside the constructor

Person.prototype.sayHello = function () {
Alert ("Name:" + + ", Sex:" +;

var p = new Person ("Yang over" under the banyan Tree, "male");
P.sayhello ();

P.privatemethod ()//here will be an error, private method cannot be called by the instance
alert (p._privatevariable);//display: undefined

Description: A function defined in a class's constructor is a private method, whereas a variable declared in a constructor with Var is also a private variable. (However, the notion of private members in a strongly typed language like C # is different, such as not being invoked in a method other than a constructor)

Similarly, we can implement a package similar to the Set,get property

Copy Code code as follows:

var person = function () {
var salary = 0.0;

This.setsalary = function (value) {
salary = value;

This.getsalary = function () {
return salary;

var p = new person ();

P.setsalary (1000);
Alert (P.getsalary ());//Return 1000
alert (p.salary);/return undefined

Note: "Variable scope" in JS, "function call context (this)," closure "," prototype chain "These concepts are indeed worth a little time to understand, these lines across the past, JS novice (such as the flow of our own) level of confidence will also be small a new level.

Related Article

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

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: and provide relevant evidence. A staff member will contact you within 5 working days.