Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- Author: Thomas Truong
- Description: Prototype is one of the most common design pattern which JavaScript developers use, but the question is, is it possible to
- have private members in this design pattern in JavaScript land? To be private, or not to be private, that is the question.
- */
- /*
- Firstly, lets see how do we normally implement private in JavaScript. As shown below we normally have a closure and anything defined
- with is automatically private. The functions defined in this closure can also access the private member.
- */
- PrivatePrototype = function(){
- var privateMessage = "hello";
- this.nonPrototypeGreeting = function(){
- alert(privateMessage);
- };
- };
- /*
- This is the protoype version of the function defined above but this will fail as it does have access to privateMessage.
- */
- PrivatePrototype.prototype.prototypeGreeting = function(){
- alert(privateMessage);
- };
- /*
- If a private member is defined inside the prototype of the class as shown below, this would mean the method prototypeGreeting
- will have access to prototypePrivateMesssage but sadly any separate object instances will have the SAME private variable, as
- they are sharing the same prototype.
- */
- PrivatePrototype.prototype = function(){
- var prototypePrivateMesssage = "Hi!";
- prototypeGreeting = function(){
- alert(prototypePrivateMesssage);
- };
- };
- /*
- To implement private member for each instance, all the private variables must live within the closure. For the prototype method to
- then access the private variable it must call a function defined inside the closure which returns the variable, which in this case is
- nonPrototypeGreeting. Voila! there we have it, private member with Prototype design pattern :)
- */
- PrivatePrototype = function(){
- var privateMessage = "hello";
- this.nonPrototypeGreeting = function(){
- return privateMessage;
- };
- };
- PrivatePrototype.prototype.prototypeGreeting = function(){
- alert(this.nonPrototypeGreeting());
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement