Skip to content

Instantly share code, notes, and snippets.

@SK-CSE
Created July 2, 2019 11:58
Show Gist options
  • Save SK-CSE/673fe02068eaf89fb3cd90917fd0f7d2 to your computer and use it in GitHub Desktop.
Save SK-CSE/673fe02068eaf89fb3cd90917fd0f7d2 to your computer and use it in GitHub Desktop.
call bind apply example
// example 1
let name= {
f: "Saurabh",
l: "Kumar",
printName: function(){
console.log(this.f+ " "+this.l);
}
}
name.printName();
let name2= {
f: "Suman",
l: "Kumar"
}
// function borrowing
name.printName.call(name2);
////////////////
// Example 2
let printName = function(){
console.log(this.f+ " "+this.l);
}
printName.call(name);
printName.call(name2);
// Example 3
let printName2 = function(hometown,state){
console.log(this.f+ " "+this.l+ " "+hometown+ " "+state);
}
printName2.call(name,"Bangalore","KA");
printName2.call(name2,"khagaria","Bihar");
// Apply method : only diff is we have to pass args as an array
printName2.apply(name,["Bangalore","KA"]);
printName2.apply(name2,["khagaria","Bihar"]);
// bind method : exactly look like call method, only diff is that it return the function i.e copy of the object which can be called later
let printMyName = printName2.bind(name2,"khagaria","Bihar");
printMyName();
// console.log(printMyName());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment