版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/DreamFJ/article/details/82462636
1.常量
- ES5:
// 挂载到全局对象下面,然后配置选项不可写,如果修改PI会无效 Object.defineProperty(window,"PI2",{ value: 3.14, writable: false })
- ES6:
const PI = 3.14; // 如果修改PI会报错
2.作用域
- ES5:(只有函数作用域和全局作用域)
var callbacks = []; for(var i=0; i<=2; i++){ callbacks[i] = function(){ return i*2; } } console.table([ callbacks[0](), callbacks[1](), callbacks[2](), ]); // 以上均输出6
- ES6:(还有块级作用域)
var callbacks = []; for(let i=0; i<=2; i++){ callbacks[i] = function(){ return i*2; } } console.table([ callbacks[0](), callbacks[1](), callbacks[2](), ]); // 以上分别输出0,2,4
3.箭头函数
- ES5:(this指向调用该方法的对象)
var factory = function(){ this.a = 'a'; this.b = 'b'; this.c = { a: 'a+', b: function(){ return this.a } } } console.log(new factory().c.b()); // 输出a+
- ES6:(this指向在定义时就确定了,而不是运行时确定的)
var factory = function(){ this.a = 'a'; this.b = 'b'; this.c = { a: 'a+', b: ()=>{ return this.a } } } console.log(new factory().c.b()); // 输出a
4.默认参数
- ES5:
function f(x,y,z){ if(y===undefined){ y=7; } if(z===undefined){ z=42; } return x+y+z; } console.log(f(1,3)); // 输出46
- ES6:
function f(x, y=7, z=42){ return x+y+z; } console.log(f(1,3)); // 输出46
- eg:输入一个数组,对数组里的元素求和
-
ES5:
// 必须要用arguments function f(){ var a = Array.prototype.slice.call(arguments); var sum = 0; a.forEach(function(item){ sum += item*1; }) return sum } console.log(f(1,2,3,6)); // 输出12
- ES6:
function f(...a){ var sum = 0; a.forEach(item=>{ sum += item*1; }) return sum } console.log(f(1,2,3,6)); // 输出12
-
5.对象代理
- ES5: 定义某个属性是否可写
var Person = { name: 'es5', age: 15 }; Object.defineProperty(Person,'sex',{ writable: false, value: 'male' }); Person.sex = 'female'; console.table({ name: Person.name, age: Person.age, sex: Person.sex }); // 并没有改变sex的值,还是原来的
- ES6: 制定属性是否可写的规则
let Person = { name: 'es6', sex: 'male', age: 15 }; let person = new Proxy(Person, { get(target, key){ return target[key] }, set(target, key, value){ if(key!=='sex'){ target[key]=value; } } }); console.table({ name: person.name, sex: person.sex, age: person.age }); person.sex = 'female'; console.table({ name: person.name, sex: person.sex, age: person.age });