function this

Description

this is a reference to the function context object.

Example

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


<!--  ww w.ja v  a  2 s .  c o  m-->
<!DOCTYPE HTML>
<html>
<head>
  <script type="text/javascript">
        window.myName = "XML";
        function printMyName(){
           console.log(this.myName);
        }
        
        printMyName();     //"XML"
        
        var o = { myName: "HTML" };
        o.printMyNameForMyObject = printMyName;
        o.printMyNameForMyObject();   //"HTML"
  </script>
</head>
<body>
</body>
</html>

Click to view the demo

Note

printMyName() is defined globally and references the this object.

this is not determined until the function is called.

When printMyName() is called in the global scope, it outputs "XML" because this is pointing to window, which means this.myName evaluates to window.myName.

By assigning the function to the object o and then calling o.printMyName(), the this object points to o, so this.myName evaluates to o.myName and "HTML" is displayed.





















Home »
  Javascript »
    Javascript Introduction »




Script Element
Syntax
Data Type
Operator
Statement
Array
Primitive Wrapper Types
Function
Object-Oriented
Date
DOM
JSON
Regular Expressions