Object Oriented Programing

Object Oriented Programing (known as OOP for short) is a model of programing by using objects as events in our program other than independent step-by-step actions (known as Procedural Programming). OOP makes your code much more organized and easier to understand, and is also very useful for group projects. In this section I will explain Objects in more detail and show you how to make your own Objects.

Classes are their own structure that contain their own functions (known as methods), and their own variables (known as properties). Objects are things created from a class. For example you can look at a class as a (recipe, blueprint, template), and an object something created with the (recipe, blueprint, template). Like cookies for example, you have a cookie recipe (class) and the cookies (objects). And you could make a variety of cookies from the same recipe: big or small, peanut butter or chocolate chip.

When you create something from a class it's known as an instance (a particular object of the class). Every instance is independent of other instances, changing one will not change others. Here is how to create an object/instance:

var obj = new Object(...); // obj is an instance of the Object class.

Calling a method from an Object:

obj.methodName(...);

Getting a property of an Object:

obj.propertyName;

For example lets look at the our Human Race as a Class, then each human would be an instance of the Human class. Some properties we would have would be: height, gender, and hair color. And some methods might be: run, breath, jump, and dance.

In fact Numbers, Strings, Arrays, etc, are all Objects. And they can be defined as an instance. For example lets look at a instance of the String class and it's methods and properties (shown in Data & Functions section):

var myString = new String("Hello world"); // Create a string as an object.
myString.toUpperCase(); // Method to change the string to uppercase. => "HELLO WORLD"
myString.indexOf('W'); // Method to get a index in the string. => 6
myString.length; // returns the length Property of the string. => 11

The method that is called when an object is created is called a Constructor. Often the constructor sets the default values of the properties of instance. In this case the String Constructor [ String(string) ] takes a single argument and sets it's string property to the given argument.

In a classical sense JavaScript does not have classes. Although this is because JavaScript is based on prototyping and not class-based, we can easily create behavior the same as a class and treat it as so. In which I will consider a class in JavaScript for simplicity.

The best way to understand objects, classes, instances, and so on is to create them yourself. We can create our very own Objects, here is an outline:

function ClassName( arg* ) // Creates a class called "ClassName"
   {
   //This is the Constructor
   this.property1 = .. ;
   this.property2 = .. ;
   //End Constructor
   
   this.method1 = function( arg* ) // Makes a method called "method1"
      {
      // Code for method1
      }
 
   this.method2 = function( arg* )
      {
      // Code for method2
      }   
   }

var myObj = new Class( ... ); // Creates an instance from our Class.

this means for this particular instance. So when we say: this.variable , it means the variable belonging to the current instance. Don't get confused that it says: function ClassName(...), read it as: class ClassName(...). The class keyword is not yet implemented in JavaScript so the function keyword is used.

Lets look at some examples, here is a Ball Class:

function Ball( X, Y, R, Color ) // Creates a class called "Ball"
   {
   this.x = X; // Makes a property called: x.
   this.y = Y; // Makes a property called: y.
   this.r = R; // Makes a property called: r ( radius )
   this.color = Color; // Makes a property called: color.
   
   this.moveTo = function(newX, newY) // Makes a method called: moveTo(newX, newY).
      {
         this.x = newX; // Change the x to the new position
         this.y = newY; // Change the y to the new position
      } 
   }

var redBall = new Ball(40,40,25,"Red"); // Creates a red ball from Ball class.
var blueBall = new Ball(200,40,35,"Blue"); // Creates a blue ball from Ball class.

redBall.moveTo(60,45);


blueBall.moveTo(150,40);


arg* means 0 or more arguments. In set thoery the Kleene Star ( * ) means zero or more. This is so we can represent a variety of things from Object() to Object(arg1, arg2, arg3, ...).

If the last example was a bit too complex here is a simpler example:

function Person( name ) // Creates a class called "Person"
   {
   // It's ok to use ( this.name = name ) JavaScript can tell the difference.
   this.name = name; // Makes a property called: name. 
   
   this.sayHi = function() // alerts it's name
      {
         alert("Hello, my name is " + this.name);
      } 
   }

var person1 = new Person("Spencer");
var person2 = new Person("Calvin");

alert( person1.name ); // => "Spencer"
person1.sayHi(); // => "Hello, my name is Spencer"
person2.sayHi(); // => "Hello, my name is Calvin"


There is more than one way to create a class in JavaScript, the current why I have been showing you is the simplest in my opinion. Another way to create objects which is slightly more efficient is using: prototype. Which is a property to add methods to objects. For example here is the same Person class setup using prototype with a side-by-side comparison:

Prototype

function Person( name ){
   this.name = name;
}

Person.prototype.sayHi = function(){
   alert("Hello, my name is " + this.name);
}

Without Prototype

function Person( name ){
   this.name = name;
   
   this.sayHi = function(){
      alert("Hello, my name is " + this.name);
   }
}

 

The difference between using prototype and non-prototype is how methods are created. When you are not using prototype all methods are re-created for each instance, while prototype keeps a single method to use making it a bit more efficient. One way isn't particularly better than the other, for now I recommend choosing which is comfortable for you.

Sometimes we want to make a class that inherits the methods and properties of another more abstract class, known as Inheritance. For example lets say we have a class called Animal, and we want to make another class called Bird with the same methods and properties, but have a few extra such as fly(). We could also have Mammal and Reptile also be based on Animal. We could set this up in a tree structure known as an: inheritance tree.

Inheritance Tree
  • Child : A sub-class that was created based on a main-class.
  • Parent : A main-class that all sub-classes were based on.

Here is an example is a Parent and a Child class implemented in JavaScript:

function Parent( arg* ){
   this.P_prop = arg*;
       
   this.P_func = function(){
        // Code for parent method.
      }
   }

function Child( arg* ){ // The same arguments as the 'Parent' class.
    Parent.call(this, arg*); // This creates 'Child' to be based on 'Parent'.
    
    this.C_func = function(){
        // Code for child method.
    }
}

And here is a implementation on the Parent class Animal, and child class Bird:

function Animal( name ){
   this.name = name;
       
   this.getName = function(){
        alert("It's name is "+this.name);
      }
   }

function Bird( name ){ 
    Animal.call(this, name); 
    
    this.fly = function(){
        alert(this.name+" flew up in the sky.");
    }
}

So the Animal Class as a property: name; and a method: getName(). While the Bird class inherited the property: name and method: getName(), special to it's class it has another method fly().

var animal = new Animal("Fred");
var bird = new Bird("Jack");

// Both Animal and Bird have getName.
animal.getName(); // => Fred
bird.getName(); // =>  Jack
//animal.fly(); <-- Animal does not have a fly method
bird.fly(); // => "Jack flew up in the sky."

We went over a bunch or large topics. Here are some important points we went over:

Objects

  • Class : Contain their own functions(methods) and variables(properties) [Like a Cookie Recipe]
  • Objects : Are an instance that is created from a class [Like a cookie]
  • Constructor : Is the method called when an instance is created
  • this : Property for this particular instance

Inheritance

  • Inheritance : Is a relationship between two classes, such that the child inherits methods and properties from a more abstract parent class.
  • Child : A sub-class that was created based on a main-class.
  • Parent : A main-class that all sub-classes were based on.
  • Parent.call(this, ...) is placed in the Constructor of the child to inherit from some Parent.
Spencer Wieczorek