Last active
October 28, 2018 14:13
-
-
Save develax/1ff6324a6f513b82a8a853c500d30bd8 to your computer and use it in GitHub Desktop.
Private properties and methods in JavaScript classes. Usually don't care about privacy so I use "pseudo privacy". But if do care (if there are some special requirements for that) I use something like in the example below.
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
class jobImpl{ | |
// public | |
constructor(name){ | |
this.name = name; | |
} | |
// public | |
do(time){ | |
console.log(`${this.name} started at ${time}`); | |
this.prepare(); | |
this.execute(); | |
} | |
//public | |
stop(time){ | |
this.finish(); | |
console.log(`${this.name} finished at ${time}`); | |
} | |
// private | |
prepare(){ console.log('prepare..'); } | |
// private | |
execute(){ console.log('execute..'); } | |
// private | |
finish(){ console.log('finish..'); } | |
} | |
function Job(name){ | |
var impl = new jobImpl(name); | |
return { | |
do: time => impl.do(time), | |
stop: time => impl.stop(time) | |
}; | |
} | |
// Test: | |
// create class "Job" | |
var j = new Job("Digging a ditch"); | |
// call public members.. | |
j.do("08:00am"); | |
j.stop("06:00pm"); | |
// try to call private members or fields.. | |
console.log(j.name); // undefined | |
j.execute(); // error |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment