Object Oriented JavaScript

Don't let anyone tell you its impossible

Objectives

  • Create Constructor functions
  • Use the new keyword to instantiate an instance object
  • Create prototype methods on Constructors
  • Be able to explain when using a constructor is the right choice

After this lecture you should be able to

Lets Create a Constructor

Its very simple, I promise you

function MyConstructor(){

}

Lets Create An Instance

And we can create an instance of the constructor

function MyConstructor(){

}

var myInstance = new MyConstructor();

What is myInstance?

Lets try something different

function MyConstructor(){
    var hello = 'world';

    return hello;
}

var myInstance = new MyConstructor();

What is myInstance?

What is going on?

  • The constructor is a blueprint
  • What exactly does blueprint mean?
  • variables do not get copied to instances

This

What can we use to create variables for the instance?

function Car(make){
    this.make = make;
}

var prius = new Car('toyota');

console.log(prius);

Customize the car

Add the following properties to your car

  • amount of gas left in the tank
  • car is on or off
  • current mileage

Adding Functionality

The car is great, but we need to be able to start it

function Car(make, model){
    this.make = make;
    this.model = model;
    this.gas = 100;
    this.isOn = false;
}
Car.prototype.start = function(){
    this.isOn = true;
}

Time to Refuel

Uh oh, we ran out of gas, add a method to refuel the car.

function Car(make, model){
    this.make = make;
    this.model = model;
    this.gas = 0;
    this.isOn = false;
}
Car.prototype.start = function(){
    this.isOn = true;
}

How is this Useful?

  • Easier to read ways to create objects
  • Code reusability

Where can you use this?

  •  

When Not to Use Constructors?

Its kind of a personal thing

Questions

  • Create Constructor functions
  • Use the new keyword to instantiate an instance object
  • Create prototype methods on Constructors
  • Be able to explain when using a constructor is the right choice

oop-js

By Brooks Patton

oop-js

Object oriented javascript is fun and easy!

  • 1,184