Front end week 3: Scope - Hoa0/project-tech GitHub Wiki

Scope

Scope gaat over toegankelijkheid van variabelen, functies en objecten van een bepaalde stukje code tijdens runtime. Elke functie die wordt aangeroepen, creëert een nieuw scope. In JavaScript heb je twee soorten scopes:

  • Global Scope (variabelen die buiten een functie zijn gedefinieerd)
// Scope is standaard globaal
var name = 'Thuan-Hoa';

Variabelen binnen het globale scope kunnen worden aangeroepen en gewijzigd worden in elk ander scope.

var name = 'Thuan-Hoa';

console.log(name); // output 'Thuan-Hoa'

function logName() {
// variabele 'name' is toegankelijk in deze functie
    console.log(name); 
}

logName(); // output 'Thuan-Hoa'

Automatically Global Als een variabele in een functie zonder het trefwoord “var” gedeclareerd is, wordt het ook een global variabele (TutorialsTeacher, 2020).


 function createUserName() {
//De variabele userName wordt hier zonder het trefwoord "var" gedeclareerd
        userName = "Bill";
    }

    function modifyUserName() {
        if(userName)
            userName = "Steve";
    };

    function showUserName() {
        alert(userName);  
    }
    
    createUserName();
    showUserName(); // Bill 

    modifyUserName();
    showUserName(); // Steve 
// bron (w3school,2021)
myFunction();

// code here can use carName 

function myFunction() {
  carName = "Volvo";
}
  • Local Scope (Variabelen die binnen een functie zijn gedefinieerd) Local variabelen hebben een functie scope: ze zijn alleen toegankelijk vanuit de functie en niet buiten de functie.
//bron (Hammad Agmed, 2017)
// Global Scope
function someFunction() {
    // Local Scope #1
    function someOtherFunction() {
        // Local Scope #2
    }
}

// Global Scope
function anotherFunction() {
    // Local Scope #3
}
// Global Scope
//bron (W3schools, 2021)
// code hier kan geen gebruik maken van de variabele "carName"

function myFunction() {
  var carName = "Volvo";

  // Variabele "carName" kan hier worden gebruik

}

Bronnen

Hammad Agmed (2017, 15 februari). Unerstanding Scope in Javascript. Geraadpleegd van, https://scotch.io/tutorials/understanding-scope-in-javascript

w3schools (2021). JavaScript Scope. Geraadpleegd van, https://www.w3schools.com/js/js_scope.asp

TutorialsTeacher (2020). Scope in JavaScript. Geraadpleegd van, https://www.tutorialsteacher.com/javascript/scope-in-javascript