How JavaScript private members are implemented

Source: Internet
Author: User

I bought a book before, "JavaScript advanced Programming," Nicholas C.zakas.

Generally speaking, this book is still possible, but after reading this book still left a few problems have been bothering me, such as JS private variable implementation, prototype, and so on, after their own series of tests, and now finally figured out.

A lot of books are saying that JavaScript is not really implementing JavaScript private members, so at the time of development, the Unified Convention __ Two underscore start as a private variable.

Later, the feature of the closure in JavaScript was discovered, which completely solved the problem of JavaScript private members.

function testFn(){
 var _Name;//定义Javascript私有成员
 this.setName = function(name){
  _Name = name; //从当前执行环境中获取_Name
 }
 this.getName = function(){
  return _Name;
 }
}// End testFn
var test = testFn();
alert(typeof test._Name === "undefined")//true
test.setName("KenChen");

Test._name cannot be accessed at all, but can be accessed using object methods because closures can fetch information from the current execution environment.

Next, let's see how the shared members are implemented.

function testFn(name){
 this.Name = name;
 this.getName = function(){
  return this.Name;
 }
}
var test = new testFn("KenChen");
test.getName(); //KenChen
test.Name = "CC";
est.getName();//CC 

Next, let's look at how the class static variable is implemented.

function testFn(){
}
testFn.Name = "KenChen";
alert(testFn.Name);//KenChen
testFn.Name = "CC";
alert(testFn.Name);//CC

About Portotype, succession and so on after posting narration.

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.