What is This

// Open up a console in chrome and follow along
// Global context
this // Returns Window Object// Function in global context function globalFunc() {
return this
}
globalFunc() // Returns Window Object
globalFunc() === this // true
// Class Instance Methodclass Person {
constructor(firstName, lastName) {
this.firstName = firstName // Sets first name
this.lastName = lastName // Sets last name
}
sayName() {
// this refers to instance of class
console.log(this.firstName + ' ' + this.lastName)
}
}
let johnSmith = newPerson('John', 'Smith') // Instantiate new person
johnSmith.sayName() // Logs 'John Smith' to console
// Event Handlerslet body = document.getElementsByTagName('body')[0]
body.addEventListener('click', function(e) {
console.log(this) // logs body element when body is clicked
}
this // returns Window Objectlet body = document.getElementsByTagName('body')[0];body.addEventListener('click', function(e) {
console.log(this)
}.bind(this));
// On click, logs Window Object to Console
// Without .bind(this), it would log the body element to the console
let person = {
name: 'John Smith',
sayName: function() {
console.log('My name is ' + this.name)
}
}
let car = {
name: 'Herbie'
}
let sayName = person.sayName.bind(car)
person.sayName() // My name is John Smith
sayName() // My name is Herbie

--

--

--

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Kotlin iterate through everyday in this year

Listing Items in React Native

Setting up Signup and Basic Validations

GeoJson Decoder Integration

About multi-value return statements

Understanding Memento Pattern

If The World Continues To Shift, The Demand For Developers Will Increase More Than Ever Part II

Creating a Socket Connect with Node JS (in all controllers) and Angular 8+

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Julian Rosenthal

Julian Rosenthal

More from Medium

How to become a Web-Developer

Stack Data Structure and What does it have to do with JavaScript?

How I learned web development at university

[N] Signs You Are an [Insert Adjective] Programmer