Wednesday, September 25, 2019

Sharing private members among common instances

Suppose you have a variable that is common to all object instances, but you want to keep that private. In other languages you would create a static variable. Unfortunately, JavaScript does not support static or class variables.
You can obtain similar results in JavaScript by adding the common (i.e. shared) members to the prototype property of the constructor. In the example below, the label variable is shared among all the object instances created using the Book() constructor function. The label property is only accessible through the getLabel() prototype method.
  1. function Book(author) {
  2. var author = author; // private instance variable
  3. this.getAuthor = function () {
  4. return author; // privileged instance method
  5. };
  6. }
  7. Book.prototype = (function () {
  8. var label = "Author: "; // private prototype variable
  9. return {
  10. getLabel: function () { // privileged prototype method
  11. return label;
  12. }
  13. };
  14. }());
  15. var book1 = new Book('James Joyce');
  16. alert(book1.getLabel() + book1.getAuthor()); // => Author: James Joyce
  17. var book2 = new Book('Virginia Woolf');
  18. alert(book2.getLabel() + book2.getAuthor()); // => Author: Virginia Woolf
Run
Prototype functions are shared by all object instances. They are often used because it removes the need to create a function for each instance which saves memory and performs better. It is important to note that prototype functions have only access to prototype variables and not to private variables, such as the author variable in the example above.

No comments:

Post a Comment