wingman007

JavaScriptFactory

Jun 1st, 2016
334
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. (function(){
  2.     window.onload = function(e){
  3.         // creates objects. it looks like a constructor but it is not, because we don't use new to create objects.
  4.         // As Duglas Crocford says "I don't use new anymore"
  5.         // it creates persons
  6.         var myFactory = function(name, age){
  7.             return { // this is object representing a Person
  8.                 // 1. properties of the object. We can change them without problems. Not good.
  9. //-             name: name, // property (create as a field/instance variable)
  10. //-             age: age, // property (create as a field/instance variable)
  11.                 // 2. Only getters no setters
  12.                 // if you want to make it only for read you have to use getter without setter (accessor without mutator)
  13.                 getName: function(){ return name; }, // in this case we will not need the instance variables name and age
  14.                 getAge: function(){ return age; }, // in this case we will not need the instance variables name and age
  15.                
  16.                 intorduceYourSelf: function(){ // closure. name and age are free variables from the outer context
  17.                     // 1. using directly the free variables
  18.                     //- return "My name is " + name + ". And I am " + age + " old.";
  19.                     // or I can use the properties
  20.                     // 2. using the fields (instance variables)
  21.                     //- return "My name is " + this.name + ". And I am " + this.age + " old.";
  22.                     // 3. Using the accessors
  23.                     return "My name is " + this.getName() + ". And I am " + this.getAge() + " old.";
  24.                 }
  25.             };
  26.         };
  27.        
  28.         // use the factory to produce 2 objects of class person
  29.         var stoyan = myFactory("Stoyan", 52);
  30.         // create another object of the same class (Person)
  31.         var ivan = myFactory("Ivan", 34);
  32.        
  33.         // let's test what was produced
  34.         alert(stoyan.intorduceYourSelf()); // The result is: "My name is Stoyan. And I am 52 old."
  35.         alert(ivan.intorduceYourSelf());    // The result is: "My name is Ivan. And I am 34 old."  
  36.     }
  37. })();
Advertisement
Add Comment
Please, Sign In to add comment