Javascript - Function this object

Introduction

The function this object is a reference to the context object that the function is operating on.

When a function is called in the global scope of a web page, the this object points to window.

Consider the following:


var o = { 
  color: "blue" 
};


var j = { 
  color: "red" 
};

function sayColor(){
   console.log(this.color);
}

j.sayColor = sayColor;
j.sayColor();   //"red"

o.sayColor = sayColor;
o.sayColor();   //"blue"

The function sayColor() is defined globally but references the this object.

The value of this is not determined until the function is called.

By assigning the function to the object o and then calling o.sayColor(), the this object points to o, so this.color evaluates to o.color and "blue" is displayed.

The j.sayColor() function and o.sayColor() point to the same function even though they execute in different contexts.

Related Topics