Graduate Program KB

Foundations of Javascript - This and Prototypes

this Keyword

  • References a execution context for that call, determined by how the function was called
  • Implicit Binding:
    •   const testVar = "Initial Value"
      
        const test = {
            testVar: "testVar",
            displayName(name) {
                console.log(this.testVar + " " + name);
                //this refers to the 'test' object context
            },
        };
            test.displayName("David");
        //this is pointing at the 'test' object
        //implicit binding of the 'test' object
      

Prototypes System

  • Example
    function Greeting(name){
        this.name = name;
    }

    Greeting.prototype.ask = function(question){
        console.log(this.name + " " + question)
    }

    var testObj = new Greeting("David");
    var obj2 = new Greeting("Tom");
    testObj.ask("How are you") //this points at the testObj
    obj2.ask("How old are you") //this points to the obj2

Class Keyword

  • Syntactic sugar for the prototype System
  • Example Code that is same to example in Prototype system.
    class Greeting{
        constructor(name){
            this.name = name;
        }
        ask(question){
            console.log(this.name + " " + question)
        }
    }

    const testVar = new Greeting("David")
    const obj2 = new Greeting("Tom")

    testVar.ask("How are you")
    obj2.ask("How old are you")