Skip to content

Instantly share code, notes, and snippets.

@ultim8k
Last active August 16, 2018 12:38
Show Gist options
  • Save ultim8k/739524058925ee402cc07235c6fc9f9a to your computer and use it in GitHub Desktop.
Save ultim8k/739524058925ee402cc07235c6fc9f9a to your computer and use it in GitHub Desktop.
Modern JS kickstart
/**
* The module pattern
*/
const myObject = (function(){ // "const" is like "var" but cannot change
const myName = 'Kostas'; // This is private
const mySurname = 'Kapenekakis'; // This is private too
const sayFullName = function () {
alert(myName + ' ' + mySurname);
}
return {
alertFullName: sayFullName // Here we expose a private variable which happens to be a function
};
})();
myObject.alertFullName(); // Kostas Kapenekakis
myObject.myName // undefined
myObject.mySurname // undefined
myObject.sayFullName() // undefined is not a function
/**
* Javascript Objects
*/
// Static object
var myMotorbike = {
brand: 'Orcal',
model: 'Astor',
capacity: '125',
horsePowerWatt: 7100,
year: 2015
};
// Static object too
var myMotorbike = new Object();
myMotorbike.brand = 'Orcal';
myMotorbike.model = 'Astor';
myMotorbike.capacity = '125';
myMotorbike.horsePowerWatt = 7100;
myMotorbike.year = 2015;
// Static object again
var myMotorbike = new Object({
brand: 'Orcal',
model: 'Astor',
capacity: '125',
horsePowerWatt: 7100,
year: 2015
});
// Dynamic object (Prototype works similar to Java Class)
function Motorbike () {
return {
brand: 'Orcal',
model: 'Astor',
capacity: '125',
horsePowerWatt: 7100,
year: 2015
};
};
var myMotorbike = new Motorbike(); // This is instance of the Prototype Motorbike
// Dynamic object is more flexible
function Motorbike (brand, model, capacity) {
this.brand = brand;
this.model = model;
this.capacity = capacity; // this remains private
this.getMotorbike = function () {
return this.brand + ' ' + this.model;
};
return {
getName: this.getMotorbike
};
};
var myMotorbike = new Motorbike();
// Hey now we can have Classes too in ES6+
class Motorbike {
constructor(brand, model) {
this.brand = brand || '';
this.model = model || '';
}
getName () {
return this.brand + ' ' + this.model;
}
};
var myMotorbike = new Motorbike('Orcal', 'Astor');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment