Running Functions

Video

JavaScript Notes

JavaScript
    // HOW TO MAKE A FUNCTION RUN
    
    function rick() {
      //function declaration
      console.log("Let's get Schwifty!");
    }

    let morty = function() {
      //function expression
      //console.log("I don't think that this is such a good idea Rick.");
      console.log(this);
    };

    let summer = f1 => {
      //arrow function
      console.log("About to call another function");
      f1(); // f1.call(), f1.apply()
    };
    
    //1. parentheses make it run
    //morty();               
    

    //2. using call, apply, bind
    // rick.call(null, a,b,c,etc.);      
    // rick.apply(global, [a,b,c, etc.]);

    let o = {};
    let m = morty.bind(o);   //doesn't run function, but creates copy of function that is bound to the object 'o'
                             //the function, after it has been assigned to 'm', can then be called later
    // m();
    

    //3. passing along function references as parameters
    //summer(m);            //runs the function morty, with 'm' bound to it     
    

    //4. create a constructor to create instances of an object, and call functions from within it
    function Meeseeks() {
      //constructor function
      console.log("I'm Mr. Meeseeks.");
      this.hello = function() {
        console.log("hello");
      };
      this.goodbye = () => {};
    }
    Meeseeks.prototype.help = function() {
      //objects of type Meeseeks will be able to use this function
      console.log("Look at me.");
    };

    let me = new Meeseeks();   //5. call a constructor using new
    console.log(me);
    me.help();                 //6. call a method on the prototype of an object
    me.hello();                //7. call a method on an object
    

    // 8. Events
    // NodeJs version with EventEmitter and listener to call a function
    const EventEmitter = require("events");
    const Schwift = new EventEmitter();
    Schwift.on("schwifty", msg => {
        console.log("SCHWIFTY:", msg);
    });
    setTimeout(function() {
        Schwift.emit("schwifty", "we got schwifty");
    }, 1000);
    

    //Browser version with Event Listener to call a function
    let Schwift = new CustomEvent("schwifty");    // this line creates a custom event
    class MyObj extends EventTarget {
      //allowed to receive / listen for events
      constructor() {
        super();
      }
      log(ev) {
        console.log("EVENT", ev); // "EVENT" Schwift Event object
      }
    }

    let obj = new MyObj();
    obj.addEventListener("schwifty", obj.log);
    obj.addEventListener("schwifty", ev => console.log(ev.type)); //"schwifty"

    setTimeout(function() {
      obj.dispatchEvent(Schwift); //trigger the two event listeners for "schwift"
    }, 1000);