JSFiddle - React, Tailwind, and code Playground
HTML
<body>
<h1>Using a Closure to Hide Variables</h1>
Alright - go ahead and open up the Javascript console and add
a watch to the cb variable. The only properties you'll see of the
variable will be
<ul>
<li>getFirstName</li>
<li>getLastName</li>
<li>getName</li>
<li>setFirstName</li>
<li>setLastName</li>
</ul>
All the starage is being maintained via the var _firstName and var
_lastName variables withing the Person definition. So, rather than
having a property of the class you can access, you have private variables
that are being set and get by closure methods.
Now that you've added a watch...go ahead and put this in the console:<br />
<pre>
cb.setFirstName("Allen");
cb.setLastName("Underwood");
cb.getLastName();
</pre>
You'll again see that the variables aren't exposed, but they are indeed
being maintained.
This is encapsulation via Javascript.
</body>
JavaScript
// Code goes here
function Person(firstName, lastName){
var _firstName = firsName;
var _lastName = lastName;
this.getFirstName = function(){
return _firstName;
}
this.getLastName = function(){
return _lastName;
}
this.getName = function(){
return this.getFirstName() + " " + this.getLastName();
}
this.setFirstName = function(firstName){
_firstName = firstName;
}
this.setLastName = function(lastName){
_lastName = lastName;
}
}
// Making a global variable just so we can inspect it in Plunker
window.cb = new Person("Coding", "Blocks");