Skip to content

Instantly share code, notes, and snippets.

@ross-u
Last active February 8, 2021 06:13
Show Gist options
  • Save ross-u/4d9429d70ef93b08922f4abc783c03c0 to your computer and use it in GitHub Desktop.
Save ross-u/4d9429d70ef93b08922f4abc783c03c0 to your computer and use it in GitHub Desktop.
JavaScript OOP - this Exercise

JS - special keyword this


What is This - Exercise


For this exercise you can use Repl.it or your code editor.


Task 1

Without running the below code, try to answer the following:

What will be the value of this when whatIsThis is invoked as a standalone function, as shown in the below example ?


function whatIsThis() {
  console.log(this);
}

// What is the value of `this` ?

whatIsThis(); // ?

Task 2

Without running the below code, try to answer the following:

What will be the value of this when the below funciton is invoked as a method apartment.whatIsThis ?


// What is `this` when a function is invoked as a method ?

const apartment = {
  street: '1938 Sullivan Place',
  city: 'Metropolis',
  whatIsThis: function () {
    console.log(this);
  }
}

apartment.whatIsThis(); // -->   ?? Your Answer

Task 3

Create objects house and penthouse with the following properties and methods:

const house = {
   street: 'Your Street',
   city: 'Your City',
   color: 'Your Favourite color'
}

const penthouse = {
  street: 'Mason Street',
  city: 'Hilly Valley',
  color: 'Orange brick',
  thisArrow: () => console.log(this),
  thisRegular: function () { console.log(this) }
}

Task 4

Call the methods thisArrow and thisRegular and notice the difference in the value of this printed when using arrow function method vs. regular function method.


penthouse.thisArrow();
penthouse.thisRegular();

Bonus

Use method call() to invoke the penthouse.thisRegular method from the penthouse object with a custom this value. Method .call() takes a custom value of this as the first argument. Feel free to check the example.

As the new value of this use the object mansion provided in the code snippet below:


const mansion = {
  street: 'Oak Street',
  city: 'Springfield',
  color: 'White Oak Wood'
}


// Invoke the method `penthouse.thisRegular` using `.call()`



// Expected output: { street: "Oak Street", city: "Springfield", color: "White Oak Wood" }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment