apply3-Set the this value with Apply or Call

Set the this value with Apply or Call

by shenoyvnm

JavaScript

var avgScore = "average Score";

function avg(avgScores) {
    var sumScores = avgScores.reduce(function(curr, prev, index, array) {
        return curr + prev;
    });
    this.avgScore = sumScores / avgScores.length;
}

var gameObject = {
    name: "ma",
    scores: [20, 40, 50, 60],
    avgScore: null
}
/**1
avg(gameObject.scores);
console.log(gameObject.avgScore);
console.log(window.avgScore);**/
/** 2**/
avg.call(gameObject,gameObject.scores);
console.log(gameObject.avgScore);
console.log(window.avgScore);

/** 2 ends**/