Coding the Example

Is JavaScript an OOP Language?

Some say that JavaScript isn't a true object-oriented language; The class statement just adds a bit of glitter to prototypical inheritance that is already there (more on that in a bit). They claim that JavaScript classes are therefore not classes in the traditional sense.

JavaScript utilizes a concept called constructor functions to define objects and features (properties). Constructors allow you to effectively create as many objects as you need. When a constructor function creates a new object instance, the core functionality isn't completely copied over to the new object. Unlike "classic" OO languages, functionality is linked via a reference chain known as a prototype chain (we'll discuss this in the next module). Let's put this into practice with some real JavaScript.

Basic Example

  1. Let's first define a person with a normal function. Add this to your .js file:

    function createNewPerson(name) {
     var obj = {};
     obj.name = name;
     obj.greeting = function() {
         alert('Hi! I\'m ' + this.name + '.');
     };
     return obj;
    }
  2. Let's call the function and create a new person.

    var paul = createNewPerson('Paul');
    paul.name;
    paul.greeting();
  3. Let's simplify this with a constructor function:

    function Person(name) {
     this.name = name;
     this.greeting = function() {
         alert('Hi! I\'m ' + this.name + '.');
     };
    }

    Constructor functions don't return anything or explicitly create an object, they basically just define properties. The this keyword basically means that the name value passed to the constructor call will be the same one used by both the name property and greeting() method. Please note that constructor names typically begin with a capital letter to be more recognizable.

  4. Let's create some objects!

    var person1 = new Person('Bob');
    var person2 = new Person('Sarah');
  5. Here are the properties:

    person1.name
    person1.greeting()
    person2.name
    person2.greeting()

    When calling the properties or methods you need to start with person1 or person2. The name property and greeting methods have the same syntax, but need to be called separately. This is one of the reasons the this keyword is so important, so that each will use its own values and not the others.

Let's look back at the constructor calls.

var person1 = new Person('Bob');
var person2 = new Person('Sarah');

The new keyword tells the browser we are creating a new object instance, followed by the function with parameters in parentheses, and storing the result in a variable. We already know the function definition, so let's see what these objects look like now.

{
    name:'Bob',
    greeting: function() {
        alert('Hi! I\'m ' + this.name '.');
    }
}

The "Sarah" object looks the same. Rather than calling similar functions like greeting() multiple times, we can define them on the prototype(more on that later).

Creating our Finished Constructor

  1. Here's a new constructor function

    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. Let's create an object instance; put this code right below the constructor function.

    var person1 = new Person('Bob', 'Smith', 32, 'male', ['music', 'skiing']);

Challenges - Optional

  1. Create a few more objects just to get the hang of this concept.

  2. Figure out how to output different gender pronouns with the bio() method.

  3. Figure out how to take in more than two interests in the constructor function.

Other Methods of Object Instance Creation

  • The Object Literal

    1. A very common way of creating an object is an object literal.

      var person = {
       name: ['Bob', 'Smith'],
       age: 32,
       gender: 'male',
       interests: ['music', 'skiing']
    2. The main idea is that you are creating the properties and giving them values at the same time.

    3. Object literals take up less space, and are perfect if you aren't doing anything else with that object. Constructor Functions are sometimes better because you can create additional objects off of it, basically using it as a template.

  • The Object() Constructor

    1. Let's store an empty object in the person variable.

      var person1 = new Object();
    2. Fun fact, you can add properties/methods using either dot or bracket notation!

      person1.name = 'John';
      person1['age'] = 69;
      person1.greeting = function() {
       alert('Hi! I\'m ' + this.name + '.');
      };
    3. Let's combine the previous two steps and pass an object literal to the Object() constructor.

      var person1 = new Object({
       name: 'John',
       age: 69,
       greeting: function() {
           alert('Hi! I\'m ' + this.name + '.')
       }
      });
  • The create() method

    1. You can create objects based on existing ones using the create() method.

      var person2 = Object.create(person1);
    2. person2 has access to the properties/methods of person1.

      person2.name
      person2.greeting()

Resources

To learn more about OOP Basics, visit the MDN Docs.

Last updated