call-apply-bind

Javascript functions

by manoj_antony32

CSS

/* call method */
/* The call() allows for a function/method belonging to one object to be assigned and called for a different object. */
/* call() accepts an argument list, while apply() accepts a single array of arguments. */
/* * functions are also objects in javascript
* 3 methods used to control the invocation of the function
* can use call()/apply() to invoke the function immediately. bind() returns a bound function that, when executed later */

JavaScript

/* call */
let add = function(c) {   /* console.log(this.a + this.b + c) */  }
let obj = { a: 2, b: 4 }
add.call(obj, 3);
add.bind(obj, 6)();

//convert string to array using call
let toArray = function() {
/*   console.log(arguments)
  console.log([].slice.call(arguments))
  console.log([].reverse.call(arguments))
  console.log([].sort.call(arguments))
  console.log([]) */
}
toArray(2,4,6);


let mammal = function(legs) {  this.legs = legs;};
let cat = function(legs, isDomesticated) {  mammal.call(this, legs);
  this.isDomesticated = isDomesticated; }
let lion = new cat(4, false);
//console.log(lion)
/* apply */
let numArray = [1,2,3];
//console.log(Math.min.apply(null, numArray));

/* call, apply and bind */
var objt = {name:"Niladri"};
var greeting = function(a,b,c){
    return "welcome "+this.name+" to "+a+" "+b+" in "+c;
};
console.log(greeting.call(objt,"Newtown","KOLKATA","WB"));
/* apply */
var args = ["Newtown","KOLKATA","WB"];  
console.log("Output using .apply() below ")
console.log(greeting.apply(objt,args));
/* bind */
var bound = greeting.bind(objt); 
console.dir(bound); ///returns a function
console.log("Output using .bind() below ");
console.log(bound("Newtown","KOLKATA","WB")); //call the bound function