Skip to content

JavaScript: bind() vs apply() and call()

Yash edited this page Nov 14, 2019 · 1 revision
  • Call invokes the current function with provided obj(this) and comma separated list of arguments.
  • Apply invokes the current function with provided obj(this) and argument as an array.
  • Bind returns a copy of current function, So that you can invoke it later
https://stackoverflow.com/questions/15455009/javascript-call-apply-vs-bind
function greet (gender, age, name) {
    // if a male, use Mr., else use Ms.​
    var salutation = gender === "male" ? "Mr. " : "Ms. ";
    if (age > 25) {
        return "Hello, " + salutation + name + ".";
    }else {
        return "Hey, " + name + ".";
    }
}

var myObject = {
  x : 10,
  y : "Yash",
  objFun : function (args) {
    console.log("RoolNo:"+this.x+",  Name:"+this.y+", Per:"+ args);
  }
}

var defaultUser = myObject.objFun(69); // Function called to store its output

var users = {
  user1 : { x : 11, y : "Sam" },
  user2 : { x : 16, y : "User2" },
  user3 : { x : 17, y : "User3" }
};
// call(obj, args...)
// apply(obj, arrayOfVlaues)
// bind(obj, args...)         -  Binding a Funtion to Variable

var user1NotFun = myObject.objFun.call(users.user1, 69); // Function calling, returning response 
var user1Fun = myObject.objFun.bind(users.user2, 69); // Funtion Binding
var user2Fun = myObject.objFun.bind(users.user3, 70);

user1Fun();
user2Fun();

-------------------------------


function printBye(message1, message2){
    console.log(message1 + " " + this.name + " "+ message2);
}

var par01 = { name:"John" };
var msgArray = ["Bye", "Never come again..."];

printBye.call(par01, "Bye", "Never come again...");
//Bye John Never come again...

printBye.call(par01, msgArray);
//Bye,Never come again... John undefined

//so call() doesn't work with array and better with comma seperated parameters 

//printBye.apply(par01, "Bye", "Never come again...");//Error
//"TypeError: CreateListFromArrayLike called on non-object

printBye.apply(par01, msgArray);
//Bye John Never come again...

var func1 = printBye.bind(par01, "Bye", "Never come again...");
func1();//Bye John Never come again...

var func2 = printBye.bind(par01, msgArray);
func2();//Bye,Never come again... John undefined
//so bind() doesn't work with array and better with comma seperated parameters

Clone this wiki locally