/js-objects-prototypes

Primary LanguageJavaScriptOtherNOASSERTION

General Assembly Logo

JavaScript Prototypes

Prerequisites

Objectives

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

Preparation

  1. Fork and clone this repository.
  2. Change to the new directory.
  3. Install dependencies.
  4. Create and checkout a new branch, training

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 should we get behavior in our custom objects?

Remember wonderWoman?

const wonderWoman = {
  name: 'Diana Prince',
  alias: 'Wonder Woman',

  usePower: function() {
    return 'Deflects bullets with bracelets'
  }
}

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

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

Code along: add methods to prototypes

  1. Create usePower and attach it to the constructor function's prototype.
  2. Create a method to say the hero's name and alias. Attach it to the prototype.
  3. Create batman and wonderWoman. Call the method just attached.
  4. Observe that this method isn't part of objects created using the constructor function.

Lab: Add Methods to Prototypes

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

  1. All content is licensed under a CC­BY­NC­SA 4.0 license.
  2. All software code is licensed under GNU GPLv3. For commercial use or alternative licensing, please contact legal@ga.co.