Created
May 5, 2015 22:56
-
-
Save thesabbir/b9d87352e21fd13ec8d7 to your computer and use it in GitHub Desktop.
How to use .call() and .apply()
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
| /* CallApply.js | |
| * How to use .call() and .apply() | |
| * Author : Sabbir Ahmed | |
| * Mail : <mail[at]thesabbir.com> | |
| * Date : 6-May-2015 | |
| */ | |
| // Lets create a User Object | |
| var User = function(name, age){ | |
| // Properties | |
| this.name = name; | |
| this.age = age; | |
| // Methods | |
| this.find = function() { | |
| // Returns a JSON Object | |
| return { | |
| "name" : this.name, | |
| "age" : this.age | |
| }; | |
| } | |
| } | |
| // Lets define a function that changes name property | |
| // Note: this equals GLOBAL | |
| var changeName = function(name, note) { | |
| console.log(note); | |
| this.name = name; | |
| }; | |
| // Lets create an admin user | |
| var admin = new User('sabbir', 20); | |
| // Here is how we call method of an object | |
| // Call find method. this equals to admin object. | |
| // lets log the result | |
| console.log("Untouched: "); | |
| console.log(admin.find()); | |
| // Remove name. Using a function. | |
| // Note: we are suppliying the value of this. | |
| changeName.call(admin, 'Firoz', 'After Typo Fixed: '); | |
| // Log | |
| console.log(admin.find()); | |
| //Same thing using .apply() | |
| changeName.apply(admin, ['Supreme Leader Aladin', 'After no more democracy: ']); | |
| console.log(admin.find()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment