JavaScript (JS) Bytes 3

JavaScript

First lets discuss the relationship between all the three (bind, call and apply). They all are used to attach a reference of this to the calling function.

The bind() method creates a new function that, when called, has its this keyword set to the provided value.And the cool thing is, after we bind() a value we can use the function just like it was any other normal function. We could even update the function to accept parameters

The call() method calls a function with a given this value and arguments provided individually.

The main differences between bind() and call() is that the call() method:

  1. Accepts additional parameters as well
  2. Executes the function it was called upon right away.
  3. The call() method does not make a copy of the function it is being called on.

call() and apply( serve the exact same purpose. The only difference between how they work is that call() expects all parameters to be passed in individually, whereas apply() expects an array of all of our parameters. 

//JS Bytes 3

function factMata(){    
    return {
        arr : [4,9,16,25,36,49,64,81,100],
        compute : function(x) {
            var compArr = [];
            this.arr.map(function(t){
             compArr.push(x * t);   
            });
            return compArr;
        }
    };
   
}

var trial = function(d) {
    console.log("Bind/call/apply Trail"+ this.compute(d));
   // console.log("After computation "+this.compArr);
}
//Bind allows you to call and invoke the function later
/*
var test = trial.bind(factMata());
var nArr = test(3);
console.log(nArr);
*/
trial.call(factMata(),3);
trial.apply(factMata(),[3]);


 

In the example above feel free to remove the comments and change and play with different all the invocation methods. The only way to become a JavaScript ninja is to get your hands dirty ! Untill next time folks ! 

Add new comment

Restricted HTML

  • Allowed HTML tags: <a href hreflang> <em> <strong> <cite> <blockquote cite> <code> <ul type> <ol start type> <li> <dl> <dt> <dd> <h2 id> <h3 id> <h4 id> <h5 id> <h6 id>
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.
CAPTCHA
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.