DEV Community

Code_Regina
Code_Regina

Posted on

Week 19: Closures and the keyword 'this'

This week focus was on Closures and the keyword 'this' from Colt Steele The Advanced Web Developer Bootcamp.

 -Intro to Closures
 -Closures in the Wild 
 -Intro to keyword 'this' 
 -'this' with Functions and "use strict"
 -Object/Implicit Binding 
 -Explicit Binding 
Enter fullscreen mode Exit fullscreen mode

Intro to Closures

A closure is a function that makes use of variables defined in outer functions that have previously returned

Alt Text

Closures in the Wild

What are some use cases for closures?

In other languages there exist support for variables that can not be modified externally. We call those private variables, but JavaScript doesn't have private variables built-in to the language. That is where closures can help.


function classRoom() {
 var instructors = ["Elie", "Colt"]; 
return {
  getInstructros: function() {
    return instructors; 
}, 
addInstructors: function(instructor) {
   instructor.push(instructor); 
     return instructors; 
   }
  }
}

Enter fullscreen mode Exit fullscreen mode

Closure exists when an inner function makes use of variables declared in an outer function which has previously returned

Closure does not exist if you do not return an inner function and if that inner function does not make use of variables returned by an outer function.

JavaScript will only remember values that are being used inside of the inner function, but not all variables defined in the outer function.

We can use closures to create private variables and write better code that isolates our logic and application.

 ###Intro to keyword 'this' 
Enter fullscreen mode Exit fullscreen mode

A reserved keyword in JavaScript
Usually determined by how a function is called also known as execution context.
Can be determined using four rules
-Global
-Object/Implicit
-Explicit
-New

Global Context

When 'this' is not inside of a declared object
console.log(this)

'this' with Functions and "use strict"

When 'this' is not inside of a declared object


console.log(this); 

function whatIsThis() {
  return this; 
}

whatIsThis(); 

function variablesInThis() {
  this.person = "Elie"
}

variablesInThis() 

console.log(person); 

Enter fullscreen mode Exit fullscreen mode

Strict Mode


"use strict"

console.log(this); 

function whatIsThis() {
  return this; 
}

whatIsThis(); 

"use strict"

function variablesInThis() {

this.person = "Elie"; 
}

variablesInThis(); 

Enter fullscreen mode Exit fullscreen mode

Object/Implicit Binding

When the keyword 'this' IS inside of a declared object


var person = {
  firstName: "Elie", 
  sayHi: function() {
    return "Hi " + this.firstName; 
   }, 
determineContext: function() {
   return this === person; 
   }
} 

person.sayHi(); 

Enter fullscreen mode Exit fullscreen mode

Explicit Binding

Choose what we want the context of 'this' to be using call, apply, or bind

Alt Text

Top comments (0)