Last active
June 29, 2020 07:52
-
-
Save JoseJPR/3d0f9ca7d081a8d17e1b552b248fadd0 to your computer and use it in GitHub Desktop.
JavaScript Closure with Properties and Variables. In this example you can see that work with closure you can define properties or variables after use it.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Title: JavaScript Closure with Properties and Variables. | |
* | |
* Description: In this example you can see that work with closure you can define | |
* properties or variables after use it. | |
* | |
* More Info: https://developer.mozilla.org/es/docs/Web/JavaScript/Closures | |
*/ | |
// Define Anonymous Function for encapsulate from Root Scope. | |
(function () { | |
// Create Main Closure Function. | |
function vehicle() { | |
// Set default properties and values. | |
this.statusDoors = 'close'; | |
// Contructor for return all instance. | |
function constructor () { | |
return this; | |
} | |
// Toggle and Get Status Door Methods. | |
this.toggleStatusDoors = function () { | |
return this.statusDoors === 'close' ? this.statusDoors = 'open' : this.statusDoors = 'close'; | |
} | |
this.getStatusDoors = function () { | |
return this.statusDoors; | |
} | |
// Set and Get Color Methods. | |
this.setColor = function (value) { | |
return value ? color = value : 'Color value is required.'; | |
} | |
this.getColor = function () { | |
return color; | |
} | |
// Set default variables and values. | |
let color = 'black'; | |
// Return all Closure Object. | |
return constructor; | |
} | |
// Define Vehicle (A) with Vehicle Object. | |
const vehicleA = vehicle()(); | |
// Get Status Door and Color. | |
console.log(vehicleA.getStatusDoors()); | |
console.log(vehicleA.getColor()); | |
// To check that you can´t set color without value. | |
console.log(vehicleA.setColor()); | |
// Toggle and Get Status Doors method. | |
console.log(vehicleA.toggleStatusDoors()); | |
console.log(vehicleA.getStatusDoors()); | |
// Set and Get New Color Value. | |
console.log(vehicleA.setColor('white')); | |
console.log(vehicleA.getColor()); | |
/** | |
* If you log vehicleA object you can see that you hace all properties and method less the variable color. | |
*/ | |
// console.log(vehicleA); | |
})(); | |
/** | |
* If you log vehicleA object return that is not defined, this is normal you are in different scope. | |
* The scope goes from the inside out and not the opposite. | |
*/ | |
// console.log(vehicleA); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment