Last active
June 7, 2018 14:50
-
-
Save jmcmaster/d66801610f5ce1774e868bd249134340 to your computer and use it in GitHub Desktop.
this - Part 2 - Explicit Binding
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
// Explicit Binding | |
// call, apply, bind | |
// these methods allow you to explicitly state what the 'this' keyword is going to be in any given function | |
// Example 1 | |
var sayName = function(lang1, lang2, lang3) { | |
console.log('My name is ' + this.name + ' and I know ' + lang1 + ', ' + lang2 + ', and ' + lang3); | |
}; | |
var stacy = { | |
name: 'Stacy', | |
age: 34 | |
}; | |
var languages = ['JavaScript', 'Ruby', 'Python']; | |
// function.call(thisArg, arg1, arg2, ...) | |
// .call will immediately invoke the fn | |
sayName.call(stacy, languages[0], languages[1], languages[2]); | |
// Example 2 | |
var sayName = function(lang1, lang2, lang3, lang4) { | |
console.log('My name is ' + this.name + ' and I know ' + lang1 + ', ' + lang2 + ', ' + lang3 + ', and ' + lang4); | |
}; | |
var stacy = { | |
name: 'Stacy', | |
age: 34 | |
}; | |
var languages = ['JavaScript', 'Ruby', 'Python']; | |
// function.apply(thisArg, [argsArray]) | |
// .apply will immediately invoke the fn | |
sayName.apply(stacy, languages); | |
// Example 3 | |
// .bind will return a new fn that you can invoke later | |
var newFn = sayName.bind(stacy, languages[0], languages[1], languages[2]) | |
newFn(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment