Created
November 25, 2012 21:26
-
-
Save jackfranklin/4145446 to your computer and use it in GitHub Desktop.
call() and apply() in JS
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
| /*** | |
| * Call and Apply in JavaScript | |
| ***/ | |
| var me = { | |
| firstName: "Jack", | |
| lastName: "Franklin", | |
| fullName: function(title, middleName) { | |
| return title + ". " + this.firstName + " " + middleName + " " + this.lastName; | |
| } | |
| }; | |
| var bob = { | |
| firstName: "Bob", | |
| lastName: "Bobbington" | |
| }; | |
| console.log(me.fullName("Mr", "Thomas")); | |
| console.log(me.fullName.call(bob, "Master", "Bob")); | |
| console.log(me.fullName.apply(bob, ["Master", "Bob"])); | |
| function add() { | |
| var args = [].slice.call(arguments); | |
| var sum = 0; | |
| for(var i = 0; i < args.length; i++) { | |
| sum += args[i]; | |
| } | |
| return sum; | |
| }; | |
| console.log(add(1,2,3)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment