ES5/ES3对比,重新思考ES5带来的提升

getter/setter 存取器

es5:

var o = {a:1, b:2, get c() {return this.a + this.b}, set c(val) {this.a = val - this.b}};
console.log(o.c);
//3 o.c = 6; console.log(o.a); //4

 

 

es3:

var o = {a: 1, b: 2, getc: function() {return this.a + this.b}, setc: function(val) {this.a = val - this.b}};
console.log(o.getc());
//3 o.setc(6); console.log(o.a); //4

 

 

可以看到使用了getter/setter后虚拟属性c用起来更加自然,与普通属性达到了相同的使用形式。同时,如果要对现有属性在存/取时每次都添加逻辑,可以把数据属性改写成存取器属性,这样既不用改写现有业务代码,同时也达到了代码复用以及保证添加了的逻辑没有遗漏。

 

数组迭代方法

es5:

var arr = [2,6,34,9,65,4,7];

var arr2 = arr.filter(function(val) {return val > 10});

console.log(arr2);  //[34, 65]

 

es3:

var arr = [2,6,34,9,65,4,7];

var arr2 = [];

for (var i in arr) {

  if (arr[i] > 10)

    arr2.push(arr[i]);

}

console.log(arr2);  //[34, 65]

 

 

数组的迭代方法让我们做一些数组操作的代码变得极为简洁,极大的提高了可读性和可维护性。其它的迭代方法还有indexOf, lastIndexOf, forEach, every, some, map, reduce和reduceRight。

 

String.prototype.trim()

es5:

console.log('  123  456  '.trim());  //'123  456'

 

es3:

console.log('  123  456  '.replace(/(^\s+)|(\s+$)/g, ''));  //'123  456'

 

再也不用用正则表达式去空格了,在表单验证中极其有用。

 

Date.now()

es5:

console.log(Date.now());  //1494091196365

 

es3:

console.log(new Date().getTime());  //1494091196365

 

获取当前时间毫秒数不再需要先创建对象了,由此带来开发效率与运行效率的双重提升。

 

结尾的可选逗号

es5中的字面量对象和数组在末尾可以追加逗号,便于复制、粘贴、剪切等操作:

{a: 1, b:2,}
[3,4,5,]

 

JSON相关

es5:

JSON.parse('{"a": 3}')

es3:

eval('({"a": 3})')

es5中的JSON序列化和反序列号相比es3更方便和安全。

 

继承

es5:

var Rectangle = function (id, x, y, width, height) {
    Shape.call(this, id, x, y);
    this.width  = width;
    this.height = height;
};
Rectangle.prototype = Object.create(Shape.prototype);
Rectangle.prototype.constructor = Rectangle;

 

es3:

var Rectangle = function (id, x, y, width, height) {
    Shape.call(this, id, x, y);
    this.width  = width;
    this.height = height;
};
Rectangle.prototype = new Shape();

 

es5使用Object.create可以实现正确的继承。而es3缺乏Object.create则只能写出不完美的继承(子类还未实例化父类已经实例化执行了构造函数,构造函数不带参数可能报错)

 

属性描述器

es5引入了属性描述器,从而使我们可以设定某个属性的可写性、可枚举性和可配置性。有了这些,我们可以定义不可更改的常量,也可以定义在for循环中不循环的属性(隐藏起来)。

posted @ 2017-05-17 00:12  898310778  阅读(3851)  评论(0编辑  收藏  举报