Week 19: Closures and the keyword 'this'
Code_Regina
Posted on October 11, 2020
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
Intro to Closures
A closure is a function that makes use of variables defined in outer functions that have previously returned
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;
}
}
}
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'
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);
Strict Mode
"use strict"
console.log(this);
function whatIsThis() {
return this;
}
whatIsThis();
"use strict"
function variablesInThis() {
this.person = "Elie";
}
variablesInThis();
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();
Explicit Binding
Choose what we want the context of 'this' to be using call, apply, or bind
Posted on October 11, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
July 16, 2022