Skip to content

Instantly share code, notes, and snippets.

@devdays
Created December 8, 2014 19:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save devdays/43440c6aa436b8a8ae0e to your computer and use it in GitHub Desktop.
Save devdays/43440c6aa436b8a8ae0e to your computer and use it in GitHub Desktop.
function displayQuote() {
// the value of "this" will change; depends on
// which object it is called through
console.log(this.memorableQuote);
}
var williamShakespeare = {
"memorableQuote": "It is a wise father that knows his own child.",
"sayIt" : displayQuote
};
var markTwain = {
"memorableQuote": "Golf is a good walk spoiled.",
"sayIt" : displayQuote
};
var oscarWilde = {
"memorableQuote": "True friends stab you in the front."
// we can call the function displayQuote
// as a method of oscarWilde without assigning it
// as oscarWilde’s method.
//"sayIt" : displayQuote
};
williamShakespeare.sayIt(); // true, true
markTwain.sayIt(); // he didn’t know where to play golf
// watch this, each function has a method call()
// that allows the function to be called as a
// method of the object passed to call() as an
// argument.
// this line below is equivalent to assigning
// displayQuote to sayIt, and calling oscarWilde.sayIt().
displayQuote.call(oscarWilde); // ouch!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment