Home > Web Front-end > JS Tutorial > body text

Detailed explanation of implementation examples of javascript private members

伊谢尔伦
Release: 2017-07-27 11:22:06
Original
1437 people have browsed it

Many books say that Javascript cannot truly implement Javascript private members, so during development, it is agreed that __ starting with two underscores is a private variable.

Later, I discovered the feature of closures in Javascript, 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");
Copy after login

test._Name cannot be accessed at all, but it can be accessed using object methods because closures can obtain information from the current execution environment.

Next let’s take a look at how 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
Copy after login

Next let’s take a look at how class static variables are implemented

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

The above is the detailed content of Detailed explanation of implementation examples of javascript private members. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!