Javascript - Function this value augment

Introduction

The apply() and call() can augment the this value inside of the function.

Consider the following example:

var j = { color: "red" };
var o = { color: "blue" };

function sayColor(){
    console.log(this.color);
}
sayColor.call(j);      //red
sayColor.call(o);      //blue

sayColor() is defined as a global function.

The advantage of using call() (or apply()) to augment the scope is that the object doesn't need to know anything about the method.

Related Topic