浅谈 ECMAScript 和 JavaScript

ES5与ES3基本保持兼容,较大的语法修正和新功能加入,将由JavaScript.next完成。

什么是ECMAScript?

http://baike.baidu.com/link?url=G1T8nGWaC0r3o-TDiDXZhgt75zEHYrG6TLxRfFjJvxpxNZHgy0Hk1Dz0RSsymSl-25oE0uUba81B7JSBc5Cw0a

ECMAScript 5.1

浏览器支持

Opera 11.60

Internet Explorer 9+

Firefox 4

Safari 5.1+

Chrome 13

"use strict" 严格模式(可靠,安全),字符串会被旧版浏览器忽略,放心使用

添加到Object上的构造器

Object.getPrototypeOf

Object.getOwnPropertyDescriptor

Object.getOwnPropertyNames

Object.create

Object.defineProperty

Object.defineProperties

Object.seal

Object.freeze

Object.preventExtensions

Object.isSealed

Object.isFrozen

Object.isExtensible

Object.keys

对象的属性:可以枚举、删除、修改

Array扩展:

Array.prototype.indexOf

Array.prototype.lastIndexOf

Array.prototype.every

Array.prototype.some

Array.prototype.forEach

Array.prototype.map

Array.prototype.filter

Array.prototype.reduce

Array.prototype.reduceRight

代码:

 1 'use strict';
 2 
 3 /**
 4  * 全局JSON对象
 5  * 序列化JSON.stringify ECMAScript值->JSON
 6  * 反序列化JSON.parse   JSON->ECMAScript值
 7  *
 8  * JSON.parse(text[, reviver)
 9  * JSON.stringify(value[, replacer[, space)
10  */
11 
12 var result = JSON.parse('{"a": 1, "b": 2}');
13 console.log(result);
14 console.log(result.b);
15 
16 var result = JSON.parse('{"a": 1, "b": 2}', function (key,value) {
17     if(typeof value == 'string') {
18         console.log('string');
19         return parseInt(value);
20     }else {
21         console.log('other');
22         return value;
23     }
24 });
25 
26 console.log(result.b);
27 
28  var nums = {
29     "first": 7,
30     "second": 14,
31     "third": 13
32  };
33 
34 /**
35  * 添加replacer过滤函数操作
36  * space代表缩进空格
37  */
38 var luckyNums = JSON.stringify(nums, function(key, value){
39     if (value == 13) {
40         return undefined;
41     } else {
42         return value;
43     }
44 }, 2);
45 
46 console.log(luckyNums);
47 
48 var cat = {};
49 
50 Object.defineProperty(cat, 'name', {
51     value: 'Maru',
52     writable: false,
53     enumerable: true,
54     configurable: false
55 });
56 
57 Object.defineProperty(cat, 'skill', {
58     value: 'exploring boxes',
59     writable: true,
60     enumerable: true,
61     configurable: false
62 });
63 
64 for(var key in cat) {
65     console.log(key + ': ' + cat[key]);
66 }
67 
68 console.log(Array.isArray('No u'));
69 console.log(Array.isArray(['No', 'u']));
70 
71 
72 var mike = JSON.stringify({mike: 'taylor'});
73 console.log(mike); //{"mike":"taylor"}
74 console.log(typeof mike); //string
75 
76 /**
77  * Array.isArray()直接写在了构造器上,而不是prototype对象上
78  */
79 
80 /**
81  * Function.prototype.bind(thisArg[, arg1[, arg2,...)
82  */
83 function locate() {
84     console.log(this.location);
85 }
86 
87 function Maru(location) {
88     this.location = location;
89 }
90 
91 var maru = new Maru('some words');
92 var locateMaru = locate.bind(maru);
93 
94 locateMaru();

typeof 运算符判断原始类型

instanceof 运算符要求程序员明确地了解变量的数据类型,比如:

1 console.log(oStringObject instanceof String);

原始类型:Undefined, Null, Number, Boolean, String

类型转换:

ECMAScript规定所有的对象都具有 toString()方法。

parseInt()、parseFloat()

强制类型转换:

Boolean()

Number()

String()

Boolean(""); //false - 空字符串

Boolean(null); //false - null

Boolean(0); //false - 零

强制转换成字符串和调用 toString() 方法的唯一不同之处在于,对 null 和 undefined 值强制类型转换可以生成字符串而不引发错误:

var s1 = String(null); //"null"

var oNull = null;

var s2 = oNull.toString(); //会引发错误

引用类型:

var o = new Object();

1. Object 对象 (自身用处不大)

2. Boolean 对象(很少使用,不易理解,尽量避免使用)

3. Number 对象(只要可能,都使用数字的原始表示法。尽量避免使用

new Number(68).toFixed(2); // 68.00, 返回具有指定位数小数的数字的字符串表示

4. String 对象

length 属性

charAt()、charCodeAt()访问字符串索引的单个字符

charAt() 返回单个字符

charCodeAt() 返回单个字符的字符代码

concat() 把一个或多个字符串连接到String对象的原始值上,

一般都是用"+"连接,很少用concat()

indexOf()、lastIndexOf() 返回指定字符串的位置

indexOf() 从字符串的开头开始检索字符串

lastIndexOf() 从字符串的结尾检索字符串

slice()、substring() 都是返回要处理的字符串子串

slice(startIndex[, endIndex])

substring(startIndex[, endIndex])

对于负数参数,slice() 方法会从后往前数,substring() 方法则将其作为 0 处理(也就是说将忽略它)。

与 concat() 方法一样,slice() 和 substring() 方法都不改变 String 对象自身的值。它们只返回原始的 String 值,保持 String 对象不变 。

toLowerCase()、toLocaleLowerCase()、toUpperCase() 和 toLocaleUpperCase()

toLocaleLowerCase()、toLocaleUpperCase()更安全

代码:

 1 console.log(window.document.domain);
 2 console.log(window.document.lastModified);
 3 console.log(window.document.referrer);
 4 console.log(window.document.title);
 5 console.log(window.document.URL);
 6 
 7 document.write('Hello World!');
 8 document.write('Have a nice day!');
 9 
10 document.writeln('Hello World!');
11 document.writeln('Have a nice day!');
12 
13 var test1 = 'hi',test2 = 'hello';
14 var test = 'hi', age = 25;
15 
16 //没有初始化值的变量也是合法的
17 var test3;
18 
19 var test;
20 var $test;
21 var $1;
22 var _$te$t2;

ECMAScript 的核心: 函数

return 语句后面的代码都不会执行

注释:如果函数无明确的返回值,或调用了没有参数的 return 语句,那么它真正返回的值是 undefined。

arguments 对象

1. 无需明确命名参数,也可以传入参数

2. 检测参数个数

3. 模拟函数重载

ECMAScript 不会验证传入的参数和定义的参数量是否相等

ECMAScript 的函数实际上是功能完整的对象

Function 对象的length属性声明了函数期望的参数个数

Function 对象的toString()方法可以打印出函数的文本,进行调试

闭包,是指函数可以使用函数之外的变量

使用闭包要小心,因为它们可能会变得非常复杂。

代码:

 1 /**
 2  * 信息函数
 3  * @param msg
 4  */
 5 function sMessage(msg) {
 6     if(msg == 'bye') {
 7         // 永远不执行
 8         return;
 9     }
10 
11     alert(msg);
12 }
13 
14 sMessage('bye');
15 
16 
17 function sMessage() {
18     if(arguments[0] == 'bye') {
19         // 永远不执行
20         return;
21     }
22 
23     alert(arguments[0]);
24 }
25 
26 sMessage('byeccc');
27 
28 /**
29  * 检测有多少个参数
30  */
31 function howManyArgs() {
32     alert(arguments.length);
33 }
34 
35 howManyArgs('some', 'text');
36 howManyArgs();
37 howManyArgs('some');
38 
39 
40 function doAdd(arg1, arg2) {
41     if(arguments.length > 0) {
42         alert('有实参');
43     }else {
44         alert('无实参');
45     }
46 }
47 
48 function test() {
49     return 'some text';
50 }
51 
52 //打印函数所期望的参数个数
53 console.log(doAdd.length);
54 console.log(test.length);
55 
56 // 简单的闭包实例
57 var message = 'text';
58 
59 function myFunction () {
60     console.log(message);
61 }
62 
63 // 函数的内部函数是一个闭包
64 var iBaseNum = 10;
65 
66 function addNum(iNum1, iNum2) {
67     function doAdd() {
68         return iNum1 + iNum2 + iBaseNum;
69     }
70 
71     return doAdd();
72 }
73 
74 console.log(addNum(1, 2));