resource11 / js-objects-prototypes

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

General Assembly Logo

JavaScript Prototypes

Prerequisites

Objectives

  • Define methods on custom objects by attaching them to the prototype

Prototypes

In the previous lesson, we saw how to use constructors to de-duplicate effort in creating new objects that share attributes. We learned that we should never define a method inside a constructor function. So how do we get behavior in our custom objects?

Remember batman?

let batman = {
  name: 'Bruce Wayne',
  alias: 'The Bat-man',

  power: function() {
    return 'Super wealthy and super pissed off';
  }
}

We made a nice Hero constructor to take care of the attributes.

const Hero = function(name, alias) {
  this.name = name;
  this.alias = alias;
};

Next:

  1. Create a method to say the hero's name and alias. Attach it to the prototype.
  2. Create batman and superman. Call the method just attached.
  3. Explain that power is a singleton method, and should be attached directly to the object. It's really just data IN DISGUISE!

Lab: Add Methods to Prototypes

Change the run tracker code you made in the previous lesson to use prototypes.

Source code distributed under the MIT license. Text and other assets copyright General Assembly, Inc., all rights reserved.

About

License:Other


Languages

Language:JavaScript 100.0%