Created
November 12, 2015 13:49
-
-
Save ehernandez-xk/8390ef5bab2ebc9d0545 to your computer and use it in GitHub Desktop.
javascript - call, bind and apply
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
var person = { | |
firstname: "eddy", | |
lastname: "hernandez", | |
fullname: function () { | |
return this.firstname + " " + this.lastname; | |
} | |
} | |
console.log(person.fullname()); | |
//************** | |
//the statement this is pointing to Window object, | |
//but we can control 'this' keyboard points to another object using | |
// bind, call or apply | |
var logName = function (lang1, lang2) { | |
console.log("Logged: " + this.fullname() + " can speack: " + lang1 + " " + lang2); | |
console.log("-------------") | |
}.bind(person); | |
logName("es", "en"); | |
var logName2 = function (lang1, lang2) { | |
console.log("Logged: " + this.fullname() + " can speack: " + lang1 + " " + lang2); | |
console.log("-------------") | |
}; | |
// bind: creats a copy of the function and binds to an object. | |
var seeName = logName2.bind(person); | |
seeName("es", "en"); | |
//************* | |
//call: also executed the function and we can pass parameters | |
logName2.call(person, "ex", "xe"); | |
//apply: the same thing like call but it receives an array, it helps when you want to pass a bunch of numbers. | |
logName2.apply(person, ["in", "bi"]); | |
//IFEE | |
(function (lang1, lang2) { | |
console.log("Logged: " + this.fullname() + " can speack: " + lang1 + " " + lang2); | |
console.log("-------------") | |
}).apply(person, ["ya", "hoo"]); | |
//************* | |
// funciton borrowing | |
var person2 = { | |
firstname: "pepe", | |
lastname: "trueno" | |
} | |
// if I want person2 uses the function of person, it can borrow the function. doing a copy of the function | |
console.log(person.fullname.apply(person2)); | |
/*output console | |
pepe trueno | |
*/ | |
//************* | |
// function currying: create a copy of a function but with some preset parameters | |
function multiply (a, b) { | |
return a*b; | |
} | |
// we are sending 'this', means that the function multiplyByTwo new parameter. instead of sending (this, 2, 2) | |
// in this case 10 will be the third parameter. | |
var multiplyByTwo = multiply.bind(this, 2); | |
console.log(multiplyByTwo(10)); | |
/*output console | |
20 | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment