+ 1

What is the best way to fake Classes in JavaScript?

is there a better way to fake classes with private members in JavaScript? function Animal(name) { // private var age = 1; // public this.name = name; this.getAge = function() { return age; } this.celebrateBirthday() { age++; } } var cat = new Animal('Kitty'); cat.celebrateBirthday(); console.log(cat.age); // undefined console.log(cat.getAge()); // 2 pro: private is not accessible from outside con: no chance for inheritance /testing. thanks!

6th Dec 2016, 8:36 PM
codinator
codinator - avatar
1 Odpowiedź
0
You can actually define classes in JavaScript: https://developer.mozilla.org/es/docs/Web/JavaScript/Referencia/Classes And although JS does not have native private functionality, you can use closures instead: https://developer.mozilla.org/en-US/Add-ons/SDK/Guides/Contributor_s_Guide/Private_Properties
18th May 2017, 2:53 PM
Álvaro