JavaScript: Scope and the Variable this

JavaScript: Scope and the Variable this

February 29, 2020
var x = 'hello, world!'; // this is in the global scope!

////////////////////

function greet(thing) {
  console.log(this + " says greetings, " + thing);
}

greet.call("Cami", "earthlings") // Cami says greetings, earthlings

////////////////////

var person = {
  name: "Samantha",
  greet: function(thing) {
    console.log(this + " says greetings, " + thing);
  }
}

person.greet('neighbor'); // Samantha says greetings, neighbor
person.greet.call(person, 'neighbor'); // Samantha says greetings, neighbor

////////////////////

function greet2(thing1, thing2) {
  console.log(this + " says greetings, " + thing1);
  console.log("But " + thing2 + " doesn't like " + this);
}

greet2.call('Samantha', 'Maya', 'Angelina')
// Samantha says greetings, Maya
// But Angelina doesn't like Samantha

greet2.apply('Samantha', ['Maya', 'Angelina'])
// Samantha says greetings, Maya
// But Angelina doesn't like Samantha

////////////////////

var boundGreeting = greet2.bind('Noah')

boundGreeting('Christian', 'Ben')
// Noah says greetings, Christian
// But Ben doesn't like Noah

One Comment

  1. Camilla December 23, 2022 at 8:54 pm - Reply

    Hello! I could have sworn I’ve been to this blog before but after reading through some of the post I realized it’s new to me.
    Nonetheless, I’m definitely happy I found it and I’ll be book-marking and checking back often!

Leave A Comment