Review of Week 2 Day 4 Learning Objectives (pt2)

4. Define an arrow function

const returnValue = (val) => val;

This simple construct will create a function that accepts val as a parameter, and returns val immediately. We do not need to type return val, because this is a single-line function.

Identically, we could write

const returnValue = (val) => {
  return val;
};

5. Given an arrow function, deduce the value of this without executing the code

function fDAdder(arr) {
  console.log(this);

  return arr.reduce((acc, ele) => { return acc + ele; });
};

fDAdder([1, 2, 4, 6]);

If we use a function declaration style function, the this variable is set to the global object (i.e. Object [global] in Node.JS and Window in your browser).

const adder = (arr) => {
  console.log(this);
  arr.reduce( (acc, ele) => sum += ele );
};
adder([1, 2, 4, 6]);

In this example, we use a fat arrow style function. Note that when we declare a funciton like this this becomes

7. Define a method that references this on an object literal

const pokemon = {
  firstname: 'Pika',
  lastname: 'Chu',
  getPokeName: function () {
    const fullname = `${this.firstname} ${this.lastname}`;
    return fullname;
  }
};

console.log(pokemon.getPokeName());

8. Utilize the built in Function#bind on a callback to maintain the context of this

const pokemon = {
  firstname: 'Pika',
  lastname: 'Chu',
  getPokeName: function () {
    const fullname = `${this.firstname} ${this.lastname}`;
    return fullname;
  }
};

const logPokemon = pokemon.getPokename.bind(pokemon);

logPokemon('sushi', 'algorithms'); // Pika Chu loves sushi and algorithms

9. Given a code snippet, identify what this refers to

function Person(name) {
  // this.name = name; 
  // let that = this;

  setTimeout(function() {
    // console.log(this); // => Window
    // console.log(that); // => [Function] => Person
    // this.sayName(); // => no method error
    that.sayName();
  }, 1000);
}

Person.prototype.sayName = function() {
  console.log(this.name);
};

const jane = new Person("Jane");