Intermediate JavaScript - Function Invocation

Question Click to View Answer

What does the following code print to the console?

result = function surfer() {
  return this === window;
}();
console.log(result);
true

There are four different ways to invoke functions in JavaScript and this example demonstrates invocation as a function. The keyword "this" equals window for functions that are invoked as functions.

What does the following code print to the console?

phone = {
  ring: function () {
    return this === phone;
  }
}
console.log(phone.ring());
true

The ring() function is invoked as a method, so the "this" keyword is assigned to the phone object.

What does the following code print to the console?

hat = function () {
  return this;
}

obj1 = {
  check: hat
}

obj2 = {
  check: hat
}

console.log(obj1 === obj1.check())
console.log(obj2 === obj2.check())
true
true

When the hat() method is bound to obj1, "this" refers to obj1. When the hat() method is bound to obj2, "this" refers to obj2. The "this" keyword for a given method can be assigned to different objects depending on the invocation context for the method.

What does the following code print to the console?

function Builder () {
  this.self = function () {
    return this;
  }
}
b = new Builder();
console.log(b.self() === b);
true

For constructor functions, "this" refers to the object that's created by the constructor function.

dude = {
  greet: "hi",
  bye: "peace"
}

function a () {
  return this.greet + ", " + this.bye;
}

console.log(a.apply(dude));
"hi, peace"

The apply() method is defined for function objects and accepts an object as the first parameter. The object that's passed to apply() as an argument is assigned to "this" when the function is invoked.

What does the following code print to the console?

function full_name (first, last) {
  return first + " " + last + ": " + this.age;
}

shredder = {
  age: 37
}

console.log(full_name.apply(shredder, ["evil", "badguy"]));

evil badguy: 37

The apply() method takes an array of arguments as the second parameter.

What does the following code print to the console?

function sum (x, y) {
  return this.name + ", the sum is " + (x + y);
}

person = {
  name: "Phil"
}

console.log(sum.call(person, 2, 2));
Phil, the sum is 4

The call() method is similar to apply(), but it takes the parameters as arguments instead of an array.

Use the teamCity() function and teams array to create the following array ['Giants from New York', 'Seahawks from Seattle'].

function Team(name, city) {
  this.name = name;
  this.city = city;
}

teams = [
  new Team("Giants", "New York"),
  new Team("Seahawks", "Seattle")
]

function teamCity () {
  return this.name + " from " + this.city;
}
result = []
teams.forEach(function (team) {
  result.push(teamCity.call(team));
});
console.log(result);