A Pen by AngeloDeleon on CodePen.
Created
September 20, 2018 18:10
-
-
Save RaDeleon/935d0dd14d554ee86aba60b5c5472ec3 to your computer and use it in GitHub Desktop.
FSW 14: This Keyword
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment