Skip to content

Instantly share code, notes, and snippets.

@John-Dormevil
Last active May 19, 2017 12:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save John-Dormevil/44be503333fb6df2975f7b1fcfa396f8 to your computer and use it in GitHub Desktop.
Save John-Dormevil/44be503333fb6df2975f7b1fcfa396f8 to your computer and use it in GitHub Desktop.
Basic way to create object in JS (private/public encapsulation simulation)
var Personne = function(n, f) {
//use var to declare private variable
var name = n;
var firstname = f;
//one of private methode
var private_cry = function() {
console.log(`YES I TOLD YOU!!! MY NAME IS ${name}`);
}
//the best way to declare public methode
Personne.prototype.setName = function(n) {
name = n;
}
Personne.prototype.setFirstname = function(f) {
firstname = f;
}
Personne.prototype.getName = function() {
return name;
}
Personne.prototype.getFirstname = function() {
return firstname;
}
//give public access to the private methode
Personne.prototype.cry = function() {
return private_cry();
}
}
//clear the console before show any output
console.clear();
//create a Persone object pass in the construtor arguments
var p = new Personne('vile', 'jules');
//use some getter and setter
p.setName('dorme');
p.setFirstname('jean');
console.log(p.getFirstname());
console.log(p.getName());
//make a personne cry
p.cry();
//show an object
console.log(p);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment