ECMAScript 5 新特性

 

Strict模式

開啓strictjavascript

在文件頭部,或者在一個function頭部內,添加‘use strict’或者「use strict」。java

 

Strict模式的限制,以及違反時出現的異常:git

  • 新定製了將來可能會使用的一些保留字段 "implements", "interface", "let", "package", "private", "protected", "public", "static", and "yield"

那麼這些保留字也就不能做爲變量,常量、參數了。github

Uncaught SyntaxError: Unexpected strict mode reserved word

 

  • 八進制的數字不能做爲字面量來用了

在以前的版本中。若是前綴爲 0,則 JavaScript 會把數值常量解釋爲八進制數,若是前綴爲 0 和 "x",則解釋爲十六進制數。正則表達式

例如:var a=0379, 會做爲8進制。0x12,會做爲16進制。json

可是在strict 模式下,就不容許使用8進制字面量了。瀏覽器

Uncaught SyntaxError: Decimals with leading zeros are not allowed in strict mode.
  •  escape、unescape 方法要對8進制處理 

這一項,基本上用不到的。不須要關注。函數

 

  •  全部變量聲明必須有var

之前的版本中,聲明一個變量,若是不使用var修飾的話,該變量會做爲一個global變量。在strict 模式下取消這一項了。測試

Uncaught ReferenceError: a is not defined
  • 不建議使用eval,arguments

下面三種狀況下不能使用eval, arguments :es5

1)不能在賦值操做符(=)的左邊,

2)不能出如今後綴(++, --)操做符的左邊

3)不能與一元操做符(delete, void, typeof, ++, --, +, -, ~, !)結合使用

4)不能做爲函數的形參

5)還有不少其餘情形

上述三種狀況下,違反時會出現:

Uncaught SyntaxError: Unexpected eval or arguments in strict mode

 總之一句話,就是不能亂用eval, arguments

 

  • 不能使用caller,callee

不能使用Arguments對象的callee,不能使用Function對象的caller

Uncaught TypeError: 'caller', 'callee', and 'arguments' properties may not be accessed on strict mode functions or the arguments objects for calls to them
  • 對象字面量的屬性不能重複

{a:1,b:’23’,a:123} 這樣的代碼是不被容許的。這個在Chrome上測試居然是能夠的。

  • 一個函數的做用域不會被默認綁定給global,而是綁定爲null或者undefined
  • 不能使用delete語句、with語句
  • 形參不能出現重名的狀況

 

 

內置對象變化

一、 Object添加了一些靜態方法

1)繼承相關方法:create、getPrototypeOf 
2)屬性相關方法:defineProperty、 defineProperties、 getOwnPropertyDescriptor、getOwnPropertyNames、 keys

3)防篡改方法:preventExtensions、isExtensible、seal、isSealed、freeze、isFrozen

 須要注意的是,這些方法所有是Object對象的,不是prototype,也就是說,不是每個javascript對象都能用的。


2Function 
1)Function.prototype添加了bind()方法。 
2)規範化了一個函數對象的屬性caller,用於指向調用當前函數的函數的引用。 
3)prototype是不可枚舉的 


3Array對象 
(1)判斷方法:添加了靜態方法Array.isArray(obj)用於判斷obj是否爲一個Array對象的實例。 
(2)索引方法:添加了兩個用於查找指定項索引的方法indexOf()和lastIndexOf()。查找時使用全等(===)進行匹配。 
(3)迭代方法:添加了every()、some()、forEach()、map()、filter()方法。 
(4)縮小方法:添加了reduce()和reduceRight()方法。 
其中3)4)是和Java8的Stream API遙相呼應哈。

 

4String對象 
  添加了trim()方法。 
5Date對象 
  添加了Date.now()、Date.prototype.toJSON()等方法。 
6RegExp對象 
  在ES3中,使用正則表達式字面量時共享一個RegExp實例,而在ES5中,每次使用正則表達式字面量時都要建立新的RegExp實例,就像使用RegExp構造函數同樣。

7JSON對象 
  添加了原生JSON內建對象。 

var obj = {'a':1,'b':new Date(),'c':1};
console.log(obj);
var jsonstr =JSON.stringify(obj)
console.log(jsonstr)
var obj1 = JSON.parse(jsonstr);
console.log(obj1)

 

此外,各個瀏覽器對 ES 5的支持狀況參見:http://kangax.github.io/compat-table/es5/

相關文章
相關標籤/搜索