this-sample4

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

by shenoyvnm

JavaScript

// We have two objects. One of them has a method called avg () that the other doesn't have​
// So we will borrow the (avg()) method​

//reduce method is javascript's methd
//very well explained

//https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce

var gameController = {
    scores: [20, 10, 30, 40, 50],
    avgScore: null,
    players: [{
        name: "tommy",
        age: 23
    }, {
        name: "samy",
        age: 43
    }, {
        name: "raju",
        age: 33
    }, ]

}

var appController = {

    scores: [50, 100, 60, 90, 100],
    avgScore: null,
    avg: function () {
        debugger;
        var sumOfScores = this.scores.reduce(function (prev, cur, index, array) {
            return prev + cur;
        });

        this.avgScore = sumOfScores / this.scores.length;
    }
}

//If we run the code below,​
// the gameController.avgScore property will be set to the average score from the appController object "scores" array​

// Don't run this code, for it is just for illustration; we want the appController.avgScore to remain null
/**1**/
/**
gameController.avgScore = appController.avg();
console.log(gameController.avgScore);
console.log(appController.avgScore); **/
//**1 ends**/
/**2**/

appController.avg.apply(gameController,gameController.scores);
console.log(gameController.avgScore);
console.log (appController.avgScore); // null

gameController.avgScore = appController.avg();
console.log(gameController.avgScore);

console.log (appController.avgScore); // null



/**2 ends **/