Skip to content

14 July 2019 Lecture Summary .this

AaaaT edited this page Jul 21, 2019 · 1 revision

summary of today - by Jakob

this in objects. points to the instance of the object that the function is called on.

let Rectangle = function(sideLen) {
    this.sideLen = sideLen;
    this.area = function() {
        return sideLen*sideLen;
    }
    this.setSideLen = function(newSideLen) {
        this.sideLen = newSideLen;
    }
}

let firstRectangle = new Rectangle(2);
console.log(firstRectangle.area()); // prints 4

let secondRectangle = new Rectangle(1);
console.log(secondRectangle.area()); // prints 1

firstRectangle.setSideLen(5);
console.log(firstRectangle.area()); // prints 25
console.log(secondRectangle.area()); // still prints 1

scope scope is a concept where names are looked up from the inner most scope and outwards, this has some special cases in JS where functions (and var) ignores block scopes.

function fun() {
    let a = "a1";
    let b = "b1";
    {
        let a = "a2";
        console.log(a); // looks for something called "a", looks in current scope and finds variable with value "a2".
        console.log(b); // looks for something called "b", looks in current scope, doesn't find it, goes to the previous scope and looks there, it finds variable b with the value "b1".
    }
}

functions (and var) are special...

function get() {
    return 0;
}
function fun() {
    console.log(get()); // looks for something named get, nothing found in current scope, checks the next level and finds the function returning 0.
}
function get() {
    return 0;
}
function fun() {
    function get() {
        return 1;
    }
    console.log(get()); // looks for something named get, finds the function returning 1.
}
function get() {
    return 0;
}
function fun() {
    {
        function get() { // NOTE, functions ignore block scope, this is moved up to the scope of fun().
            return 2;
        }
    }

    console.log(get()); // looks for something named get, finds the function returning 2.
}

Clone this wiki locally