Use this to reference function context in JavaScript

Description

The following code shows how to use this to reference function context.

Example


<!--  ww  w . java  2 s  .c o  m-->
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
window.color = "A";
var o = { color: "B" };

function sayColor(){
document.writeln(this.color);
}

sayColor();  //A
o.sayColor = sayColor;
o.sayColor(); //B

</script>
</head>
<body>
</body>
</html>

Click to view the demo

The code above generates the following result.

Use this to reference function context in JavaScript