General Assembly

Closures & this

Wilson Espina

Review

What did we do last lesson?

Closures & This

Learning Objective

Learning Objectives

At the end of this class, you will be able to:

  • Understand and explain closures.
  • Instantly invoke functions.
  • Implement the module pattern in your code.
  • Build a function factory.
  • Understand and explain Javascript context.

Closures & This

Agenda

  • Classes (lesson 14)
  • Closures
  • IIFE's
  • The Module Pattern
  • this

Closures & This

Classroom Resources

  • Pull changes from the wilson-espina/jsd-9-resources repo to your computer
  • In your editor, open the following folder: Documents/JSD/jsd-9-resources/15-closures-this

Prototypal Inheritance

Classes

Prototypal Inheritance

Class vs Prototype

class vs prototype

Prototypal Inheritance

Class Keyword


function Vehicle(colour) {
  this.colour = colour;
}
								

Constructor

=


class Vehicle {
  constructor(colour) {
    this.colour = colour;
  }
}
								

Class Keyword (ES6)

Prototypal Inheritance

Extends and Super Keyword


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

Car.prototype = new Vehicle();
								

Constructor + Prototype

=


class Car extends Vehicle() {
  constructor(colour) {
    super(colour);
  }
}
								

Class + Extends & Super Keywords (ES6)

Code along

Code Along

Open up: 00-classes-codealong

Code Along

Lab - Refactor Code to Use Classes

Exercise

Type of Exercise

  • Individual / pair

Location

  • starter-code > 01-classes-lab

Timing

10mins

  1. Refactor the Item, Clothing, and Household prototypes and constructors to recreate the same prototype chain using class keyword syntax.
  2. Test your work in the browser console.

Closures & This

Closures & This

Closures & This

The Module Pattern

Module pattern overview

Closures & This

Closures

Closures & This

The Module Pattern

Closures

Closures & This

Global Scope

  • A variable declared outside of a function is accessible everywhere, even within functions. Such a variable is said to have global scope.
Global scope

Closures & This

Function Scope

  • A variable declared within a function is not accessible outside of that function. Such a variable is said to have function scope, which is one type of local scope.
Function scope

Closures & This

Block Scope

  • A variable created with let or const creates local scope within any block, including blocks that are part of loops and conditionals.
  • This is known as block scope, which is another type of local scope.
Block scope

Closures & This

Closure

  • A closure is an inner function that has access to the outer (enclosing) function’s variables.
Closure 1

Closures & This

Closure

  • A closure is an inner function that has access to the outer (enclosing) function’s variables.
Closure 2

Closures & This

Building Blocks of a Closure

  1. Nested functions.
Nested functions

Closures & This

Building Blocks of a Closure

  1. Nested functions.
  2. Scope: inner function has access to outer function’s variables.
Inner functions

Closures & This

Building Blocks of a Closure

  1. Nested functions.
  2. Scope: inner function has access to outer function’s variables.
  3. A return statement: outer function returns reference to inner function.
Return statement

Code along - Closures

Code Along

Open up: 02-closures-codealong

Code Along

Closures & This

Closures: Key Points 🔑

  1. Closures have access to the outer function’s variables (including parameters) even after the outer function returns.
  2. Closures store references to the outer function’s variables, not the actual values.
  3. In JavaScript, closures are created every time a function is created, at function creation time.

Code along - Closures

Code Along

Open up: 02-closures-codealong

Code Along

Closures & This

What are Closures used for?

Notepad
  1. Turning an outer variable into a private variable.
  2. Namespacing private functions.
  3. Creating function factories (any function which is not a class or constructor that returns a new object).

Lab - Closures

Exercise

Key Objective

  • Understand and explain closures

Type of Exercise

  • Individual / pair

Location

  • starter-code > 03-closures-lab

Timing

12 mins

  1. Follow the instructions in app.js to build and test code that uses closure.

Closures & This

IIFE

Closures & This

Immediatley-Invoked Function Expression

"Iffy"

Closures & This

The Module Pattern

Module pattern IIFE

Closures & This

Immediatley-Invoked Function Expression (IIFE)

  • A function expression that is executed as soon as it is declared.
  • Used to avoid global namespace issues.

Closures & This

IIFE based on a function expression

  • Make a function expression into an IIFE by adding () to the end (before the semicolon).

const countDown = function() {
  let counter;
  for(counter = 3; counter > 0; counter--) {
    console.log(counter);
  }
}();

							

Closures & This

IIFE based on a function expression

  • Make a function expression into an IIFE by adding () to the end (before the semicolon).
IIFE function expression

Closures & This

IIFE based on a function declaration

  • Make a function declaration into an IIFE by wrapping in parentheses and adding () to the end.

(function countDown() {
  let counter;
  for(counter = 3; counter > 0; counter--) {
    console.log(counter);
  }
})();
							

Closures & This

IIFE based on a function declaration

  • Make a function declaration into an IIFE by wrapping in parentheses and adding () to the end.
IIFE function declaration

Code along - IIFEs

Code Along

Open up: 04-iife-codealong

Code Along

Closures & This

The Module Pattern

Closures & This

The Module Pattern

Module pattern overview

Closures & This

The Module Pattern

  • Using an IIFE to return an object literal.
  • The methods of the returned object can access the private properties and methods of the IIFE (closures!), but other code cannot do this.
  • This means specific parts of the IIFE are not available in the global scope.

Closures & This

Building a Module


const counter = function () {
  let count = 0;
    return {
      reset: function () {
        count = 0;
      }
      getCount: function () {
        return count;
      }
      increment: function () {
        count++
      }
    }
}();
							

Closures & This

Building a Module

Building a module 1

Closures & This

Building a Module

Building a module 2

Closures & This

Building a Module

Building a module 3

Closures & This

Benefits of the Module Pattern

  • Keeps some functions and variables private.
  • Avoids polluting the global scope.
  • Organises code into objects.

Code along - Modules

Code Along

Open up: 05-modules-codealong

Code Along

Exercise - Create a Module

Exercise

Type of Exercise

  • Individual / pair

Location

  • starter-code > 06-modules-exercise

Timing

10 mins

  1. In app.js, complete the module so it exports methods for the behaviours described in the comment at the top of the file.
  2. When your code is complete and works properly, the statements at the bottom of the file should all return the expected values in the console.
  3. BONUS: Add a "tradeIn" method that lets you change the make of the car and refuels it. Be sure the getMake method still works after doing a tradeIn.

Closures & This

this

Closures & This

What is Context in JavaScript?

  • Context in JavaScript is related to objects. It refers to the object within the function being executed.
  • this refers to the object that the function is executing in.

Closures & This

How is Context Decided?

  • At runtime (where your javascript code is executed when you run it).
  • Based on how the function is called.

Closures & This

Context Rules

SITUATION WHAT this MAPS TO

1. method invocation

the object that owns the method

2. constructor function

the newly created object

3. event handler

the element that the event was fired from

4. function invocation

the global object (window)

5. function invocation (strict mode)

undefined

6. arrow function

the context of the caller

Code along - Context

Code Along

Open up: 07-this-codealong

Code Along

Exercise - This Exercise

Exercise

Key Objective

  • Understand and explain closures

Type of Exercise

  • Individual

Location

  • starter-code > 08-this-exercise

Timing

6 mins

  1. In app.js, read through the code without running it.
  2. Predict the results of the two console.log statements.
  3. Run the code and check the results against your predictions. If the results were different, identify why.

Closures Lab

Exercise

Key Objective

  • Understand and explain closures

Type of Exercise

  • Individual / pair

Location

  • starter-code > 09-closures-lab

Timing

12 mins

  1. In your editor, open app.js and read the instructions.
  2. Create the createShippingCalculator function described in the instructions.
  3. Create 2 variables that call the function you created with different argument values.
  4. Check the console output and verify that you get the expected results.

Closures & This

Learning Objective

Learning Objectives

  • Understand and explain closures.
  • Instantly invoke functions.
  • Implement the module pattern in your code.
  • Build a function factory.
  • Understand and explain Javascript context.

Closures & this

Look Ahead to Next Lesson

  • Explain what CRUD is.
  • Explain the HTTP methods associated with CRUD.
  • Implement Firebase in an application.
  • Build a full-stack app with CRUD functionality.

Closures & this

Final Project Timeline

Final lessons schedule

Closures & this

Homework

Closures & this

Exit Ticket

(Lesson #15)