Created
May 28, 2019 00:38
-
-
Save Millsky/dfb2c287af6090f4910b9f0fe9a3008f to your computer and use it in GitHub Desktop.
This file contains hidden or 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
/* Context example 1: Using Prototype */ | |
/* A functions context may be updated via the prototype */ | |
/* Currently this.speak refers to the global this, window in the browser */ | |
function animal() { | |
this.category = 'animal'; | |
/* Ran w/o context on the global scope this will throw an error */ | |
this.speak(); | |
} | |
/* Define an object with a speak property */ | |
const speakGenerator = { | |
speak: () => console.log('Spoken For'), | |
}; | |
/* When we create a new function with the updated prototype, | |
similar to bind, as it generates a new function */ | |
const human = Object.assign( | |
animal, | |
{ | |
prototype: speakGenerator, | |
} | |
); | |
/* This will not trigger an error and log `Spoken For` */ | |
const me = new human(); | |
/* Context example 2: VIA other JS functions which trigger [[Call]] -> OrdinaryCallBindThis */ | |
/* A function is defined */ | |
function Product(name) { | |
this.name = name; | |
} | |
function Food(name) { | |
this.category = 'food'; | |
/* The function is called, map triggers a call to [[Call]] -> OrdinaryCallBindThis passing in this */ | |
[name].map(Product, this); | |
} | |
/* When called */ | |
console.log(new Food('cheese', 5).name); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment