Private Variables
Video
JavaScript Notes
JavaScript
// es6-object methods
// New ways of declaring methods for objects
// getters and setters for object properties
let log = console.log;
let x = 7;
let obj = {
_prop1: 1979,
get prop1( ) {
return this._prop1; // get returns another property
},
set prop1(_val) {
this._prop1 = _val; //
},
prop2: 'Alien',
x, // a new variable can also be declared as follows
prop3( ) { // function declaration can be abbreviated to just its name
log('called prop3');
}
};
log(obj.x);
log(obj.prop1);
obj.prop1 = 1980 ; or obj.prop1(1980);
log(obj.prop1);
// log(obj._prop1); //_prop1 is still accessible
// private.js
// create private variables in JS with functions
// IIFE – immediately invoked function expression
let obj = (function ( ) {
let _prop1 = 'Starman'; // this is a private variable: console.log(_prop1); will return undefined
return {
prop2: 1981,
get prop1 ( ) {
return _prop;
}
set prop1(_val) {
_prop1 = _val;
}
}
}) ( );
for(let prop in obj){
console.log(prop); // this will return prop1, and prop2, the properties of the returned object
}
Feedback
Submit and view feedback