3. Javascript - alexattia/myWiki GitHub Wiki

Some Javascript frameworks:

Table of contents :

  1. Javascript Callback functions

  2. Javascript's this

  3. Javascript's Bind Methode

  4. Javascript's Apply and Call methods

  5. AngularJS

  6. ReactsJS

Callback

Because functions are first-class objects, we can pass a function as an argument in another function and later execute that passed-in function or even return it to be executed later. This is the essence of using callback functions in JavaScript.

A callback function, also known as a higher-order function, is a function that is passed to another function (let’s call this other function “otherFunction”) as a parameter, and the callback function is called (or executed) inside the otherFunction. A callback function is essentially a pattern, and therefore, the use of a callback function is also known as a callback pattern.

var friends = ["Mike", "Stacy", "Andy", "Rick"];
​
friends.forEach(function (eachName, index){
console.log(index + 1 + ". " + eachName); // 1. Mike, 2. Stacy, 3. Andy, 4. Rick​
});
```

### This

We use the _this_ keyword as a shortcut, a referent; it refers to an object but also for precision. We use it like the pronouns in natural languages. The _this_ keyword is used to refer to an object that the function (where this is used) is bound to. The _this_ keyword not only refers to the object but it also contains the value of the object. With _this_, we can avoid difficult-to-debug errors. 
```
var person = {
    firstName: "Penelope",
    lastName: "Barrymore",
     // "this" will have the value of the person object because the person object will invoke showFullName ()​
    showFullName: function () {
        console.log(this.firstName + " " + this.lastName); //use of this
        console.log(person.firstName + " " + person.lastName); // person.firstName could attempt to access the fistName
                                                           property from the person global variable (might not be aware of)
    }
}
person.showFullName() //Penelope Barrymore
```
_this_ is used inside a function and it contains the value of the object that invokes that function.
In the global scope, when the code is executing in the browser, all global variables and functions are defined on the window object. Therefore, when we use _this_ in a global function, it refers to the global window object that is the main container of the entire JavaScript application or web page. 

The object that invokes the this Function is in context, and we can change the context by invoking the this Function with another object; then this new object is in context.
```
​// If we invoke showFullName with a different object:​
​var anotherPerson = {
firstName   :"Rohit",
lastName    :"Khan"​
};
​
​// We can use the apply method to set the "this" value explicitly—more on the apply () method later.​
​// "this" gets the value of whichever object invokes the "this" Function, hence:​
person.showFullName.apply (anotherPerson); // Rohit Khan​
​
​// So the context is now anotherPerson because anotherPerson invoked the person.showFullName ()  method by virtue of using the apply () method​
```

There are some scenarios where the _this_ keyword becomes tricky : 

http://javascriptissexy.com/understand-javascripts-this-with-clarity-and-master-it/

### Bind

**Set which object will be boung**

We use the Bind () method primarily to call a function with the this value set explicitly. It other words, bind () allows us to easily set which specific object will be bound to this when a function or method is invoked. We use Bind for setting the this value in methods and for currying functions. The need for bind usually occurs when we use the this keyword in a method and we call that method from a receiver object.
```
//            <button>Get Random Person</button>​
​//        <input type="text">​
​
​
​var user = {
    data        :[
        {name:"T. Woods", age:37},
        {name:"P. Mickelson", age:43}
    ],
    clickHandler:function (event) {
        var randomNum = ((Math.random () * 2 | 0) + 1) - 1; // random number between 0 and 1​
​
        // This line is adding a random person from the data array to the text field​
        $ ("input").val (this.data[randomNum].name + " " + this.data[randomNum].age);
    }
​
}
​
​// Assign an eventHandler to the button's click event​
$ ("button").click (user.clickHandler);
```
When you click the button, you get an error because this in the clickHandler () method is bound to the button HTML element, since that is the object that the clickHandler method is executed on.
```
 $ ("button").click (user.clickHandler.bind (user)); //replace the last line
```

**Borrow methods**

In JavaScript, we can pass functions around, return them, borrow them, and the like. And the bind () method makes it super easy to borrow methods.

```
// Here we have a cars object that does not have a method to print its data to the console​
            var cars = {
                data:[
                    {name:"Honda Accord", age:14},
                    {name:"Tesla Model S", age:2}
                ]
​
            }
​
            // We can borrow the showData () method from the user object we defined in the last example.​
            // Here we bind the user.showData method to the cars object we just created.​
            cars.showData = user.showData.bind (cars);
            cars.showData (); // Honda Accord 14​
```

###Apply and Call

The Apply and Call methods are two of the most often used Function methods in JavaScript, and for good reason: they allow us to borrow functions and set the this value in function invocation. 

**Set this**

Just as in the bind () example, we can also set the this value when invoking functions by using the Apply or Call methods. The first parameter in the call and apply methods set the this value to the object that the function is invoked upon.

```
 // global variable for demonstration​
        var avgScore = "global avgScore";
​
        //global function​
        function avg (arrayOfScores) {
            // Add all the scores and return the total​
            var sumOfScores = arrayOfScores.reduce (function (prev, cur, index, array) {
                return prev + cur;
            });
​
            // The "this" keyword here will be bound to the global object, unless we set the "this" with Call or Apply​
            this.avgScore = sumOfScores / arrayOfScores.length;
        }
​
        var gameController = {
            scores  :[20, 34, 55, 46, 77],
            avgScore:null​
        }
​
        // If we execute the avg function thus, "this" inside the function is bound to the global window object:​
        avg (gameController.scores);
        // Proof that the avgScore was set on the global window object​
        console.log (window.avgScore); // 46.4​
        console.log (gameController.avgScore); // null​
​
        // reset the global avgScore​
        avgScore = "global avgScore";
​
        // To set the "this" value explicitly, so that "this" is bound to the gameController,​
        // We use the call () method:​
        avg.call (gameController, gameController.scores);
​
        console.log (window.avgScore); //global avgScore​
        console.log (gameController.avgScore); // 46.4​
```
The apply and call methods are almost identical when setting the this value except that you pass the function parameters to apply () as an array, while you have to list the parameters individually to pass them to the call () method. More on this follows.

**Borrowing functions**

The most common use for the Apply and Call methods in JavaScript is probably to borrow functions. We can borrow functions with the Apply and Call methods just as we did with the bind method, but in a more versatile manner.

Arrays come with a number of useful methods for iterating and modifying arrays, but unfortunately, Objects do not have as many native methods. Nonetheless, since an Object can be expressed in a manner similar to an Array (known as an array-like object), and most important, because all of the Array methods are generic (except toString and toLocaleString), we can borrow Array methods and use them on objects that are array-like.

```
// An array-like object: note the non-negative integers used as keys​
                var anArrayLikeObj = {0:"Martin", 1:78, 2:67, 3:["Letta", "Marieta", "Pauline"], length:4 };
      // Make a quick copy and save the results in a real array:​
                // First parameter sets the "this" value​
                var newArray = Array.prototype.slice.call (anArrayLikeObj, 0);
​
                console.log (newArray); // ["Martin", 78, 67, Array[3]]​
​
                // Search for "Martin" in the array-like object​
                console.log (Array.prototype.indexOf.call (anArrayLikeObj, "Martin") === -1 ? false : true); // true​
​
                // Try using an Array method without the call () or apply ()​
                console.log (anArrayLikeObj.indexOf ("Martin") === -1 ? false : true); // Error: Object has no method 'indexOf'​
​
                // Reverse the object:​
                console.log (Array.prototype.reverse.call (anArrayLikeObj));
                // {0: Array[3], 1: 67, 2: 78, 3: "Martin", length: 4}​
​
                // Sweet. We can pop too:​
                console.log (Array.prototype.pop.call (anArrayLikeObj));
                console.log (anArrayLikeObj); // {0: Array[3], 1: 67, 2: 78, length: 3}​
​
                // What about push?​
                console.log (Array.prototype.push.call (anArrayLikeObj, "Jackie"));
                console.log (anArrayLikeObj); // {0: Array[3], 1: 67, 2: 78, 3: "Jackie", length: 4}​
```
⚠️ **GitHub.com Fallback** ⚠️