Skip to content

Instantly share code, notes, and snippets.

@choonkending
Last active September 21, 2016 06:31
Show Gist options
  • Save choonkending/9dd9199193aa7666e5a3ab271220e57a to your computer and use it in GitHub Desktop.
Save choonkending/9dd9199193aa7666e5a3ab271220e57a to your computer and use it in GitHub Desktop.
// https://github.com/getify/You-Dont-Know-JS/blob/master/this%20%26%20object%20prototypes/ch2.md
/*
* Called with new? Use the newly constructed object
*/
class Pokemon {
constructor(hp, mp) {
this.hp = hp;
this.mp = mp;
}
}
const pokemon1 = new Pokemon(100, 100);
const pokemon2 = new Pokemon(0, 0);
console.log(pokemon1.hp); // 100
console.log(pokemon2.hp); // 0
/*
* Called with call or apply (or bind)? Use the specified object.
*/
function pokemon() {
console.log(this.hp);
}
const charmander = { hp: 100 };
pokemon.call(charmander);
/*
* Called with context object owning the call? Use the context object
*/
function pokemon() {
console.log(this.hp);
}
const squirtle = {
hp: 100,
pokemon: pokemon
};
const bulbasaur = {
hp: 0,
squirtle: squirtle
};
console.log(squirtle.pokemon()); // 100
console.log(bulbasaur.squirtle.pokemon()); // 100
/*
* Default: undefined in strict mode, global otherwise.
*/
function pokemon() {
console.log(this.hp);
}
var hp = 100;
pokemon(); // 100
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment