Skip to content

Instantly share code, notes, and snippets.

@Shurlow
Last active September 22, 2022 11:52
Show Gist options
  • Save Shurlow/3856a5b1b5642ee5b98f5067adc6bd10 to your computer and use it in GitHub Desktop.
Save Shurlow/3856a5b1b5642ee5b98f5067adc6bd10 to your computer and use it in GitHub Desktop.

this keyword

Objectives

  • Explain the difference between a function and a method
  • Create basic objects with methods
  • Explain what the this keyword is
  • Use call/bind to mantain this context
  • Use es6 arrow functions to preserve this context

Guiding Questions

  • Explain the difference between a function and a method. What is an example of a method you use regularly?

    Your answer...

  • Label each invokation bellow as either a function or method invocation:

    Number.parseFloat('16.60')
    isNaN(0)
    ['Hello', 'World'].join(', ')
    ({ ten: function() { return 10; } }).ten()
    var obj = {}
    obj.myFunction = function() {  
      return new Date().toString()
    };
    obj.myFunction()
    var otherFunction = obj.myFunction
    otherFunction()

    Your answer...

  • Pracice creating basic objects with methods

    In a scratch js file or repl.it, code an object that represents a party!

    var party = {
      // fill in some details about the party here
      snacks: [...]
    }

    Now add a printSnacks method to your party object. Call party.printSnacks() and try running your code.

What is this

Lets test out 5 scenarios using this

Case #1

console.log(this)

Case #2

function getThis() {
  console.log(this)
  console.log('Is global:', this === window)
}

getThis()

Case #3

var party  = {
  host: 'Roger',
  snacks: ['cheetos', 'beer'],
  printSnacks: function() {
    console.log(this, this === window)
  }
}

party.printSnacks()

Case #4

var party  = {
  host: 'Roger',
  snacks: ['cheetos', 'beer'],
  printSnacks: function() {
    function innerFunction() {
      console.log(this, this === party)
    }
    innerFunction()
  }
}

party.printSnacks()

Case 5:

var party  = {
  host: 'Roger',
  snacks: ['cheetos', 'beer'],
  printSnacks: function() {
    console.log(this.snacks)
  }
}

setTimeout(party.printSnacks, 200)

What is this refering to in each of the examples above?

In your own words, write a definition for the this keyword in javascript

Use call and bind to manage this

  • What are call, bind, and apply used for?

    Your answer...

  • How can we fix cases 4 & 5 from above to use the correct context (we want this === party)?

    Your answer...

Resources

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