Skip to content

Instantly share code, notes, and snippets.

@RaDeleon
Created September 20, 2018 18:10
Show Gist options
  • Select an option

  • Save RaDeleon/935d0dd14d554ee86aba60b5c5472ec3 to your computer and use it in GitHub Desktop.

Select an option

Save RaDeleon/935d0dd14d554ee86aba60b5c5472ec3 to your computer and use it in GitHub Desktop.

Revisions

  1. RaDeleon created this gist Sep 20, 2018.
    7 changes: 7 additions & 0 deletions fsw-14-this-keyword.markdown
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,7 @@
    FSW 14: This Keyword
    --------------------


    A [Pen](https://codepen.io/radeleon/pen/GXdGzg) by [AngeloDeleon](https://codepen.io/radeleon) on [CodePen](https://codepen.io).

    [License](https://codepen.io/radeleon/pen/GXdGzg/license).
    68 changes: 68 additions & 0 deletions script.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,68 @@

    // This Concept: Window binding
    // If nothing is bound to this, it will try to go to the window

    //console.log(this);

    // ======== Implicit Binding of the this keyword
    // const hobbit = {
    // 'name': 'Samwise',
    // 'food1': "taters",
    // 'cook': function(food1) {
    // console.log(`${this.name} can cook: ${food1} and ${this.food1}`)
    // }
    // }

    // const dwarf = {
    // 'name': 'Gimli',
    // 'weapon': "axe",
    // 'fight': function() {
    // console.log(`${this.name} fights with an ${this.weapon}`)
    // }
    // }

    // // whatever is directly LEFT of the invocation is the this keyword context
    // hobbit.cook('fish');
    // dwarf.fight();


    // ======== Explicit Binding of the this keyword (Function Methods!)

    // const personInfo = {
    // 'name': 'Bob'
    // }

    // const skills = ['HTML', 'CSS', 'JS'];
    // const moreSkills = [' more HTML', 'CSS', 'JS'];


    // function introduce(skills1, skills2, skills3){
    // console.log(`Hello! My name is: ${this.name} and I like to program in: ${skills1}, ${skills2}, ${skills3}`)
    // }

    // introduce.call(personInfo, ...skills);
    // // introduce.apply(personInfo, skills);
    // //const waitForLater = introduce.bind(personInfo, ...skills);
    // // waitForLater();


    // ======== New Binding of the this keyword (Constructor Functions)

    // constructor function: to build objects
    function CordialPerson(greeter){
    this.greeter = greeter;
    this.greeting = "Hello";
    this.speak = function() {
    console.log(`${this.greeting} ${this.greeter}`)
    }
    }

    // New binding and constructor functions are bread and butter
    const jerry = new CordialPerson('Newman');
    const newman = new CordialPerson('Jerry');

    console.log(jerry);
    console.log(newman);

    jerry.speak();
    newman.speak();