Advertisement
Guest User

Untitled

a guest
May 6th, 2016
56
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.95 KB | None | 0 0
  1. /*
  2. Author: Thomas Truong
  3. Description: Prototype is one of the most common design pattern which JavaScript developers use, but the question is, is it possible to
  4. have private members in this design pattern in JavaScript land? To be private, or not to be private, that is the question.
  5. */
  6.  
  7. /*
  8. Firstly, lets see how do we normally implement private in JavaScript. As shown below we normally have a closure and anything defined
  9. with is automatically private. The functions defined in this closure can also access the private member.
  10. */
  11. PrivatePrototype = function(){
  12. var privateMessage = "hello";
  13. this.nonPrototypeGreeting = function(){
  14. alert(privateMessage);
  15. };
  16. };
  17.  
  18. /*
  19. This is the protoype version of the function defined above but this will fail as it does have access to privateMessage.
  20. */
  21. PrivatePrototype.prototype.prototypeGreeting = function(){
  22. alert(privateMessage);
  23. };
  24.  
  25. /*
  26. If a private member is defined inside the prototype of the class as shown below, this would mean the method prototypeGreeting
  27. will have access to prototypePrivateMesssage but sadly any separate object instances will have the SAME private variable, as
  28. they are sharing the same prototype.
  29. */
  30. PrivatePrototype.prototype = function(){
  31. var prototypePrivateMesssage = "Hi!";
  32. prototypeGreeting = function(){
  33. alert(prototypePrivateMesssage);
  34. };
  35. };
  36.  
  37. /*
  38. To implement private member for each instance, all the private variables must live within the closure. For the prototype method to
  39. then access the private variable it must call a function defined inside the closure which returns the variable, which in this case is
  40. nonPrototypeGreeting. Voila! there we have it, private member with Prototype design pattern :)
  41. */
  42. PrivatePrototype = function(){
  43. var privateMessage = "hello";
  44. this.nonPrototypeGreeting = function(){
  45. return privateMessage;
  46. };
  47. };
  48.  
  49. PrivatePrototype.prototype.prototypeGreeting = function(){
  50. alert(this.nonPrototypeGreeting());
  51. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement