wk 3 frontend: Scope & context - Sophievanderburg/blok-tech GitHub Wiki

📚 Desk research: Scope & context

Scope

Scope refers to the visibility of variables in the javascript code: which functions can see which variables

🌏 Global variables

All functions can see variables that are not in another function. Variables that are not in any function are called: global variables. All global variables belong to the window object.

var genre = "Pop";
    
function myGenre() {
    console.log(genre);
}

console.log(genre); // console says "Pop"
myGenre(); // console says "Pop"

🏠 local variables

When you put a variable in a function, everything outside of that function can not read it. The value of the variable will be "undefined" when you use it. You can use the variable in the function itself. These variables are called: local variables.

function myGenre() {
    var genre = "Pop";
    console.log(genre);
}

console.log(genre); // console says: Uncaught ReferenceError: genre is not defined
myGenre(); // console says: "Pop"

Function arguments (parameters) work as local variables inside functions.

The benefit of a global variable is that you can use it in multiple functions. That way you don't have to make that variable in every function.

Context

Context refers to the DOM-object to which a function belongs. The this keyword refers to the DOM-object to which the function belongs. This means that context is the value of the this keyword.

HTML

<p id="tekst">Hello there</p>
<p id="tekst2">Hello there</p>

Javascript

var text = document.querySelector("#tekst");
var text2 = document.querySelector("#tekst2");

text.addEventListener('click', wijzigTekst);
text2.addEventListener('click', wijzigTekst);

function  wijzigTekst() {
  this.textContent = "Bye then!"
}

When you click on one of the text-elements, only that element changes to "Bye Then!", because of this.textContent. This way you can use one function for multiple HTML-elements.

Used sources