Last active
May 19, 2017 12:12
-
-
Save John-Dormevil/44be503333fb6df2975f7b1fcfa396f8 to your computer and use it in GitHub Desktop.
Basic way to create object in JS (private/public encapsulation simulation)
This file contains hidden or 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
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