Private method defined in Javascript)

Source: Internet
Author: User
Tags variable scope

At one time, I thought that in the Javascript world, all methods are public and cannot be technically defined as a private method. Today I found again that I was wrong!

 
VaR person = function (name, sex) {This. name = Name; this. sex = sex; VaR _ privatevariable = ""; // Private variable // the method defined in the constructor, that is, the private method function privatemethod () {_ privatevariable = "private value"; alert ("Private method called! Private member value: "+ _ privatevariable);} privatemethod (); // The constructor can call private methods internally} person. prototype. sayhello = function () {alert ("name:" + this. name + ", Gender:" + this. sex);} var P = new person ("Yang Guo under the bodhi tree", "male"); p. sayhello (); // P. privatemethod (); // an error is reported here. The private method cannot be called by the instance alert (P. _ privatevariable); // display: Undefined

Note: The function defined in the constructor of the class is a private method. The variable declared by using VAR in the constructor is also equivalent to a private variable. (However, the concept of private members in strong-type languages such as C # is different, for example, they cannot be called in methods other than constructors)

Similarly, we can implement encapsulation similar to the set and get attributes.

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 (); // returns the 1000 alert (P. salary); // return undefined

Note: In JS, the concepts of "variable scope", "function call context (this)", "closure", and "prototype chain" are indeed worth some time to understand, these barriers have crossed, and the level of JS beginners (such as the stream of my generation) is expected to reach a new level.

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.