Last active
March 7, 2019 09:51
-
-
Save goxr3plus/b3b2b0d5f4d9c55ef0df4c8196010826 to your computer and use it in GitHub Desktop.
Javascript Bind , Call , Apply examples
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
//-----------------------Bind , Call , Apply ------------------------------// | |
//Example 1 | |
const john = { | |
name: "John", | |
age: 26, | |
job: "Teacher", | |
presentation: function(style, timeOfDay) { | |
if (style === "formal") { | |
console.log( | |
"Good " + | |
timeOfDay + | |
", Ladies and gentlemen! I'm " + | |
this.name + | |
" , I'm a " + | |
this.job + | |
" and I'm " + | |
this.age + | |
" years old ." | |
); | |
} else if (style === "friendly") { | |
console.log( | |
"Hey what's up? That's " + | |
this.name + | |
" , I'm a " + | |
this.job + | |
" and I'm " + | |
this.age + | |
" years old" + | |
" Have a nice " + | |
timeOfDay + | |
" !!" | |
); | |
} | |
} | |
}; | |
const emily = { | |
name: "Emily", | |
age: 35, | |
job: "Designer" | |
}; | |
john.presentation("formal", "morning"); | |
//Call | |
john.presentation.call(emily, "friendly", "morning"); | |
//Apply | |
john.presentation.apply(emily, ["formal", "morning"]); | |
console.log("-----------------------------"); | |
//Bind | |
const emilyFriendly = john.presentation.bind(emily, "friendly"); | |
emilyFriendly("night"); | |
//Example 2 | |
var years = [1990, 1965, 1937, 2005, 1998]; | |
function arrayCalc(arr, fn) { | |
let arrRes = []; | |
for (var i = 0; i < arr.length; i++) { | |
arrRes.push(fn(arr[i])); | |
} | |
return arrRes; | |
} | |
function calculateAge(el) { | |
return 2019 - el; | |
} | |
function isFullAge(limit, el) { | |
return el >= limit; | |
} | |
const ages = arrayCalc(years, calculateAge); | |
console.log("Ages : ", ages); | |
const fullAgeJapan = isFullAge.bind(this, 20); | |
const fullAges = arrayCalc(ages, fullAgeJapan); | |
console.log(fullAges); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment