Skip to content

Instantly share code, notes, and snippets.

@Micspr
Forked from Shurlow/this.md
Last active December 10, 2018 19:27
Show Gist options
  • Save Micspr/519302b0450158c1f427e86d4609b853 to your computer and use it in GitHub Desktop.
Save Micspr/519302b0450158c1f427e86d4609b853 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?

    Function: split() Method: string.split() The dot is the best indicator of a method.

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

    Number.parseFloat('16.60')

    Method

    isNaN(0)

    Function

    ['Hello', 'World'].join(', ')

    Method

    ({ ten: function() { return 10; } }).ten()

    Method

    var obj = {}
    obj.myFunction = function() {  
      return new Date().toString()
    };
    obj.myFunction()

    Method

    var otherFunction = obj.myFunction
    otherFunction()

    Function

  • Practice 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)

Prints the window object.

Case #2

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

getThis()

Log the window and and display as global true.

Case #3

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

party.printSnacks()

Log party and return false.

Case #4

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

party.printSnacks()

When innerFunction is called as part of the method call it refers to the window and prints the window and true. It then prints the party object and false.

Case 5:

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

setTimeout(party.printSnacks, 200)

Returns the timeout function object and prints undefined. If you alter this.snacks to just this it will print the timeout function as well.

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

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

this refers to whatever is left of the dot. More verbosely, it is a variable operating in the current scope or context and lets you operate a function in that context allowing your functions to be more modular based on the situation.

Use call and bind to manage this

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

    They are used to set the scope of the this in different ways.

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

    #4

    var party  = {
    host: 'Roger',
    snacks: ['a human kidney', 'your unhappiness'],
    printSnacks: function() {
      let innerFunction = () => {
        console.log(this, this === party)
      }
      innerFunction()
      
      // var boundFn = innerFunction.bind(this)
      // boundFn()
    }
    }
    party.printSnacks()

    #5

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

Resources

Final Repl

// const party = {
//   participants: 0,
//   noise: 10,
//   host: 'sad',
//   snacks: ['eggs', 'bacon', 'sausage']
// }

// party.printSnacks = (ele) => console.log(ele)

// party.printSnacks(party.snacks)
// party.printSnacks(party.participants)
// party.printSnacks(party.host)
// 'use strict'

var party  = {
  host: 'Roger',
  snacks: ['a human kidney', 'your unhappiness'],
  printSnacks: function() {
    let innerFunction = () => {
      console.log(this, this === party)
    }
    innerFunction()
    
    // var boundFn = innerFunction.bind(this)
    // boundFn()
  }
}


party.printSnacks()

// 'use strict'

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

setTimeout(boundSnacks, 200)

// function fn(a){
//   console.log(this, a)
// }

// fn.call({something: 'here'}, 'hi')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment