What is the best way to fake Classes in JavaScript? | Sololearn: Learn to code for FREE!

+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!

12/6/2016 8:36:53 PM

codinator

1 Answer

New Answer

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