Skip to content

Instantly share code, notes, and snippets.

@reime005
Last active August 31, 2019 10:30
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 reime005/bb1a21f139b0f5dba8390a0bdd7975c2 to your computer and use it in GitHub Desktop.
Save reime005/bb1a21f139b0f5dba8390a0bdd7975c2 to your computer and use it in GitHub Desktop.
A more complex call and apply example in JavaScript
const Example = {
name: "Hans",
age: 42,
print: function() {
console.log(`Name: "${this.name}", age: "${this.age}".`);
},
printSomething: function(extra) {
console.log(`Extra: ${extra}.`);
}
};
Example.print();
// ⇒ Name: "Hans", age: "42".
Example.print.apply(null /* or undefined */, []);
// ⇒ Name: "undefined", age: "undefined".
Example.print.call(null /* or undefined */, []);
// ⇒ Name: "undefined", age: "undefined".
Example.print.apply(Example, []);
// ⇒ Name: "Hans", age: "42".
Example.print.apply({ name: "Marius", age: 15 }, []);
// ⇒ Name: "Marius", age: "15".
Example.printSomething.apply(null, [ '"@reime005"' ]);
// ⇒ Extra: "@reime005".
Example.printSomething.call(null, '"@reime005"', "not used");
// ⇒ Extra: "@reime005".
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment