Last active
August 31, 2019 10:30
-
-
Save reime005/bb1a21f139b0f5dba8390a0bdd7975c2 to your computer and use it in GitHub Desktop.
A more complex call and apply example in JavaScript
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
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