OOP in JavaScript

  1. Let's start by looking at how you could define a person with a normal function. Add this function within the script element:
    function createNewPerson(name) {
      var obj = {};
      obj.name = name;
      obj.greeting = function() {
        alert('Hi! I\'m ' + obj.name + '.');
      };
      return obj;
    }
  2. You can now create a new person by calling this function — try the following lines in your browser's JavaScript console:
    var salva = createNewPerson('Salva');
    salva.name;
    salva.greeting();
  3. This works well enough, but it is a bit long-winded; if we know we want to create an object, why do we need to explicitly create a new empty object and return it? Fortunately, JavaScript provides us with a handy shortcut, in the form of constructor functions — let's make one now!
  4. Replace your previous function with the following:
    function Person(name) {
      this.name = name;
      this.greeting = function() {
        alert('Hi! I\'m ' + this.name + '.');
      };
    }
  5. The constructor function is JavaScript's version of a class. You'll notice that it has all the features you'd expect in a function, although it doesn't return anything or explicitly create an object — it basically just defines properties and methods. You'll see the this keyword being used here as well — it is basically saying that whenever one of these object instances is created, the object's name property will be equal to the name value passed to the constructor call, and the greeting() method will use the name value passed to the constructor call too.
    So how do we call a constructor to create some objects?
    1. Add the following lines below your previous code addition:
      var person1 = new Person('Bob');
      var person2 = new Person('Sarah');
    2. Save your code and reload it in the browser, and try entering the following lines into your JS console:
      person1.name
      person1.greeting()
      person2.name
      person2.greeting()
    Cool!

    Creating our finished constructor
    Section

    The example we looked at above was only a simple example to get us started. Let's now get on and create our final Person() constructor function.
    1. Remove the code you inserted so far, and add in this replacement constructor — this is exactly the same as the simple example in principle, with just a bit more complexity:
      function Person(first, last, age, gender, interests) {
        this.name = {
          'first': first,
          'last' : last
        };
        this.age = age;
        this.gender = gender;
        this.interests = interests;
        this.bio = function() {
          alert(this.name.first + ' ' + this.name.last + ' is ' + this.age + ' years old. He likes ' + this.interests[0] + ' and ' + this.interests[1] + '.');
        };
        this.greeting = function() {
          alert('Hi! I\'m ' + this.name.first + '.');
        };
      }
    2. Now add in the following line below it, to create an object instance from it:
      var person1 = new Person('Bob', 'Smith', 32, 'male', ['music', 'skiing']);
    You'll now see that you can access the properties and methods just like we did previously — try these in your JS console:
    person1['age']
    person1.interests[1]
    person1.bio()
    // etc.

The Object() constructorSection

First of all, you can use the Object() constructor to create a new object. Yes, even generic objects have a constructor, which generates an empty object.
  1. Try entering this into your browser's JavaScript console:
    var person1 = new Object();
  2. This stores an empty object in the person1 variable. You can then add properties and methods to this object using dot or bracket notation as desired; try these examples in your console:
    person1.name = 'Chris';
    person1['age'] = 38;
    person1.greeting = function() {
      alert('Hi! I\'m ' + this.name + '.');
    };
  3. You can also pass an object literal to the Object() constructor as a parameter, to prefill it with properties/methods. Try this in your JS console:
    var person1 = new Object({
      name: 'Chris',
      age: 38,
      greeting: function() {
        alert('Hi! I\'m ' + this.name + '.');
      }
    });

Using the create() methodSection

Constructors can help you give your code order—you can create constructors in one place, then create instances as needed, and it is clear where they came from.
However, some people prefer to create object instances without first creating constructors, especially if they are creating only a few instances of an object. JavaScript has a built-in method called create() that allows you to do that. With it, you can create a new object based on any existing object.
  1. With your finished exercise from the previous sections loaded in the browser, try this in your JavaScript console:
    var person2 = Object.create(person1);
  2. Now try these:
    person2.name
    person2.greeting()
You'll see that person2 has been created based on person1—it has the same properties and method available to it.
One limitation of create() is that IE8 does not support it. So constructors may be more effective if you want to support older browsers.

Bu blogdaki popüler yayınlar

About Android padding, margin, width, height, wrap_content, match_parent, R Class

@SerializedName and @Expose annotations