Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- (function(){
- window.onload = function(e){
- // creates objects. it looks like a constructor but it is not, because we don't use new to create objects.
- // As Duglas Crocford says "I don't use new anymore"
- // it creates persons
- var myFactory = function(name, age){
- return { // this is object representing a Person
- // 1. properties of the object. We can change them without problems. Not good.
- //- name: name, // property (create as a field/instance variable)
- //- age: age, // property (create as a field/instance variable)
- // 2. Only getters no setters
- // if you want to make it only for read you have to use getter without setter (accessor without mutator)
- getName: function(){ return name; }, // in this case we will not need the instance variables name and age
- getAge: function(){ return age; }, // in this case we will not need the instance variables name and age
- intorduceYourSelf: function(){ // closure. name and age are free variables from the outer context
- // 1. using directly the free variables
- //- return "My name is " + name + ". And I am " + age + " old.";
- // or I can use the properties
- // 2. using the fields (instance variables)
- //- return "My name is " + this.name + ". And I am " + this.age + " old.";
- // 3. Using the accessors
- return "My name is " + this.getName() + ". And I am " + this.getAge() + " old.";
- }
- };
- };
- // use the factory to produce 2 objects of class person
- var stoyan = myFactory("Stoyan", 52);
- // create another object of the same class (Person)
- var ivan = myFactory("Ivan", 34);
- // let's test what was produced
- alert(stoyan.intorduceYourSelf()); // The result is: "My name is Stoyan. And I am 52 old."
- alert(ivan.intorduceYourSelf()); // The result is: "My name is Ivan. And I am 34 old."
- }
- })();
Advertisement
Add Comment
Please, Sign In to add comment