Sunday 9 December 2018

How to define a global variable that is property of global object?

If you assign a value to any undeclared variable, then it becomes a property of global object.

In case of web pages, window is the global object. If you assign a value to any undeclared variable, then it becomes the property of the global object window.

For example,
Hello.html
<!DOCTYPE html>

<html>
 <head>
  <title>Variables</title>
 </head>
 
 <body>
  <script type="text/javascript">
 message = "Hello World";
 
 document.write("message : " + window.message);
  </script>
 </body>
</html>

As you see, the variable ‘message’ is undeclared (not declared with var, let, const keywords), but assigned with value "Hello World". In this case, it becomes the property of global object ‘window’.

What is the advantage of Global variables that are attached to global object?
You can access the global variable that is declared in one frame (or) window from another frame (or) window.

Previous                                                 Next                                                 Home

No comments:

Post a Comment