Day 65: React Course on Udemy

This & Bind

  1. In most cases, the value of "this" is determined by how a function is called.
  2. It can't be set by assignment during execution.
  3. It may be different each time the function is called.
  4. The bind method sets the value of a function's "this" regardless of how it's called.
  5. Bind creates a new function that will have "this" set to the first parameter passed to bind().

Object Literal This is created by assigning curly braces to a variable

let cat = {}

// "this" refers to the context it was created it i.e. the cat object
cat = {
  sound: 'meow',
  speak: function() {
    console.log(this.sound);
  }
};

cat.speak(); //'meow'

// in this case, we lost the cat object
// in this case the value assigned for cat.speak is no longer a method, it is now a function (detached from object)
// remember methods are functions attached to an object
// therefore "this" has lost its context

let speakFunction = cat.speak;
speakFunction(); //undefined

**Use Bind Method**

// here we chain the bind method to our speakFunction and pass in the cat object as an argument
// now when we run speakFunctionBind, it return 'meow'

let speakFunctionBind = speakFunction.bind(cat);
speakFunctionBind(); // 'meow'