日期:2014-05-16  浏览次数:20422 次

JavaScript 中两种类型的全局对象/函数

一、核心JavaScript内置对象,即ECMAScript实现提供的不依赖于宿主环境的对象
  这些对象在程序执行之前就已经(实例化)存在了。ECMAScript称为The Global Object,分为以下几种:
  1, 值属性的全局对象(Value Properties of the Global Object)。有NaN,Infinity,undefined。
   2, 函数属性的全局对象(Function Properties of the Global Object)。有 eval,parseInt,parseFloat,isNaN,isFinite,decodeURI,encodedURI,encodeURIComponent
   3,构造器(类)属性的全局对象(Constructor Properties of the Global Object)。有 Object,Function,Array,String,Boolean,Number,Date,RegExp,Error,EvalError,
RangeError,ReferenceError,SyntaxError,TypeError,URIError。
  4,其它属性的全局对象(Other Properties of the Global Object),可以看出成是Java中的静态类,可以直接用类名+点号+方法名使用。有Math,JSON。
  ECMAScript规范提到这些全局对象(The Global Object)是具有Writable属性的,即Writable为true,枚举性(Enumerable)为false,即不能用for in枚举。ECMAScript有这么一段:

  Unless otherwise specified, the standard built-in properties of the global object have attributes {[[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: true}.

  虽然规范提到The Global Object是可以被重写的,但不会有谁去重写它们的。这里仅仅做个测试。

NaN = 11 ; eval = 22 ; Object = 33 ; Math = 44 ; alert(NaN); alert(eval); alert(Object); alert(Math);

  分别取值属性的全局对象, 函数属性的全局对象,构造器(类)属性的全局对象,其它属性的全局对象NaN,eval,Object,Math。结果如下:

  结果可以看出除了NaN在IE9(pre3)/Safari不能被重写外,其它都被重写了。这里只是列举了四个,感兴趣的可以将以上所有的 The Global Object一一测试下。这里想表达的是核心JavaScript内置对象一般是可以被重写的 ,虽然没人这么干。
  下面测试下其可枚举性:

for ( var a in NaN){ alert(a); } for ( var a in eval){ alert(a); } for ( var a in Object){ alert(a); } for ( var a in Math){ alert(a); }

  所有浏览器都没有弹出,即属性不被枚举。感兴趣的可以将以上所有的The Global Object的枚举性一一测试下。当然对于有些浏览器如Firefox,某些Global Object被重写后又是可以被枚举的。

  二、宿主环境提供的全局对象/函数
  如window,alert,setTimeout,document,location等,多数浏览器都会限制其重:

window = 55 ; alert(window);

  该句在IE下会出错提示非法复制,后面的弹出框没有执行。其它浏览器则当window=55不存在,仍然弹出了window。

  再重写下alert: