Object Prototypes

Objective

  • Create a constructor function and add properties and methods to "this" keyword
  • Add properties and methods using prototype property
  • Create an object using "new" keyword

Object Constructor

Used to create an "object type" that can be used to create many objects of one type. 

var Person = function() {
  // object properties and methods assigned to this
};

var person = new Person();

Object Constructor

Properties and methods are assigned to "this" keyword.

Create an object using the constructor with the "new" keyword.

var Person = function(first,last,age,sex) {
  this.firstName = first;
  this.lastName = last;
  this.age = age;
  this.sex = sex;
  this.isHuman = true;
};

var student = new Person('John','Doe',18,'male');
var instructor = new Person('Jane','Doe',20,'female');

Prototype Property

Allows you to add properties and methods to an existing prototype.

var Person = function(first,last,age,sex) {
  ...
};

Person.prototype.sayName = function() {
  console.log('Hi my name is ' + this.firstName + ' ' + this.lastName);
};

var student = new Person('John','Doe',18,'male');

student.sayName();

Practice

Create an object constructor and add a prototype method to the object.

var Vehicle = function(wheels, weight) {
  // Set object properties here
};

// Create a prototype method changeTires on Vehicle object


// Create two vehicles (car and motorcycle) using object constructor
var car = ...
var motorcycle = ...

// Don't edit anything below this comment.
car.changeTires();
// 'Changed 4 tires.'

motorcycle.changeTires();
// 'Changed 2 tires.'

Practice Solution

var Vehicle = function(wheels, weight) {
  this.wheels = wheels;
  this.weight = weight;
};

Vehicle.prototype.changeTires = function() {
  console.log('Changed ' + this.wheels + ' tires.';
};

var car = new Vehicle(4,2000);
var motorcycle = new Vehicle(2,400);

car.changeTires()
// 'Changed 4 tires.'

motorcycle.changeTires()
// 'Changed 2 tires.'

Summary

  • Create a constructor function and add properties and methods to "this" keyword
  • Add properties and methods using prototype property
  • Create an object using "new" keyword
  • Importance of prototypes and inheritance

Object Prototypes

By Matthew Gutierrez

Object Prototypes

  • 184