当前位置:Gxlcms > JavaScript > javascript私有成员的实现方式实例详解

javascript私有成员的实现方式实例详解

时间:2021-07-01 10:21:17 帮助过:2人阅读

很多书上都是说,Javascript是不能真正实现Javascript私有成员的,因此在开发的时候,统一约定 __ 两个下划线开头为私有变量。

后来,发现Javascript中闭包的特性,从而彻底解决了Javascript私有成员的问题。

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 根本访问不到,但是用对象方法能访问到,因为闭包能从当前的执行环境中获取信息。

接下来我们看看,共有成员是怎样实现的

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

接下来在看看类静态变量是怎样实现的

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

以上就是javascript私有成员的实现方式实例详解的详细内容,更多请关注Gxl网其它相关文章!

人气教程排行