zoukankan      html  css  js  c++  java
  • The window object

      At the core of the BOM is the window object, which represents an instance of the browser. The window object serves a dual purpose in browsers, acting as the JavaScript interface to the browser window and the ECMAScript Global object. This means that every object, variable, and function defined in a web page uses windows as its Global object and has access to methods like parseInt().

    The Global Scope

      Since the window object doubles as the ECMAScript Global object, all variables and functions declared globally become properties and methods of the window object. Consider this example:

    1 var age = 29;
    2 function sayAge(){
    3   alert(this.age);
    4 }
    5 
    6 alert(window.age);
    7 sayAge();
    8 window.sayAge();
    View Code

      Despite global variables becoming properties of the window object, there is a slight difference between defining a global variable and defining a property directly on window: global variables cannot be removed using the delete operator, while properties defined on window can. For example:

     1 var age = 29;
     2 window.color = "red";
     3 
     4 // throws an error in IE < 9, returns false in all other browsers
     5 delete window.age;
     6 
     7 // throws an error in IE < 9, returns true in all other browsers
     8 delete window.color;
     9 
    10 alert(window.age);          // 29
    11 alert(window.color);        // undefined
    View Code

      Properties of window that were added via var statements have their [[Configurable]] attribute set to false and so may not be removed via the delete operator.

      Another thing to keep in mind: attempting to access an undeclared variable throws an error, but it is possible to check for the existence of a potentially undeclared variable by looking on the window object. For example:

    1 // this throws an error because oldValue is undeclared
    2 var newValue = oldValue;
    3 
    4 // this doesn't throw an error, because it's a property lookup
    5 // newValue is set to undefined
    6 var newValue = window.oldValue;
    View Code

      Keeping this in mind, there are many objects in JavaScript that are considered to be global, such as location and navigator(both discussed later in the chapter), but are actually properties of the window object.

  • 相关阅读:
    GitHub代码阅读神器,你值有拥有!
    SpringBoot项目构建成jar运行后,如何正确读取resource下的文件
    基于SpringBoot-Dubbo的微服务快速开发框架
    基于SpringBoot的Web API快速开发基础框架
    野蛮生长的前端,从杂牌军到正规军
    让Redis突破内存大小的限制
    myeclipse 8.5-10.0 安装 svn 方法
    几秒后刷新页面
    不错的Spring学习笔记(转)
    Spring学习笔记(三)-类扫描的注解
  • 原文地址:https://www.cnblogs.com/linxd/p/4514696.html
Copyright © 2011-2022 走看看