Home > Article > Web Front-end > Detailed explanation of implementation examples of javascript private members
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");
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
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
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!