/* 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
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.