1.函数扩展
ES6标准感觉越来越向传统语言靠拢了,以后写到ES6的标准都记录下:
var array = [1,2,3]; // =>操作符 array.forEach(v => console.log(v));
是不是简化了回调函数的写法。
=>可以简化函数的写法
1 var single = a => a; //single为函数;参数为a,函数体就只有a; 2 console.log(single('hello, world'));
如果没有参数;那么写法如下:
1 var log = () => { 2 alert('no param'); 3 }
注意点:
1.1.typeof运行符和普通的function一样
1 var func = a =>a; 2 console.log(typeof func); //function
1.2.this固定,不在善变
1 var obj= { 2 data:['John Backus','John Hopcroft'], 3 init:function(){ 4 document.onclick = ev => { 5 alert(this.data); 6 } 7 } 8 } 9 obj.init(); //John Backus,John Hopcroft
1.3.箭头函数不能用new
var Person = (name,age)=>{ this.name= name; this.age = age; } var p =new Person('John',33); //Uncaught TypeError: (name,age)=>{(…)
1.4.不能使用argument
var func = ()= >{ console.log(arguments); } //出错
//重要的莫过于class关键字;它提供类的创建,是JS语言的OOP编程更像JAVAC++等语言。测试了下,居然不支持
class Animal { //ES6的新型构造器 constructor(name){ this.name =name } sayName(){ console.log('My name is' + this.name); } } class Programmer extends Animal { constructor(name){ super(name); } program(){ console.log("I'm coding"); } } var animal = new Animal('dummy'), wayou = new Programmer('wayou'); animal.sayName(); wayou.sayName(); wayou.program();
1.5 源码中一个例子
var xx = [{ fn:'1' },{ fn2:'2' }] var yy = xx.map(t=>t.fn) //[ '1', undefined ] console.log(yy)
2.Object扩展
Object.is // 等价于"===";
Object.assgin(targetObj,sourceObj1,souceObj2......);
var x = Object.assign({}, undefined, { sourceMap: 'xy' }); console.log(x); // {sourceMap: "xy"}
参考博客:http://blog.csdn.net/qq_30100043/article/details/53422657
方法name的属性
console.log((new Function()).name) //anonymous var doSomething = function(){ } console.log(doSomething.bind().name); //bound
3.HTML5之FileReader的使用
转:http://blog.csdn.net/yaoyuan_difang/article/details/38582697
4.剩余操作符(rest operator) ...
var obj1 ={ 'x': 'x1', 'y': 'y1' }; var obj2 = { ...obj1, 'z': 'z1' }; console.log('obj1=', obj1); console.log('obj2=', obj2); obj1.x = 'x3'; // 深拷贝 obj2不受到obj1变化的影响。 console.log('obj1=', obj1); console.log('obj2=', obj2); obj2 = { ...obj1, 'y': 'y2' }; // 重复的y成员被替换 console.log('obj1=', obj1); console.log('obj2=', obj2); obj2 = { y: 'y3', ...obj1 }; //按照顺序替换 console.log('obj2=', obj2); // obj1= { x: 'x1', y: 'y1' } // obj2= { x: 'x1', y: 'y1', z: 'z1' } // obj1= { x: 'x3', y: 'y1' } // obj2= { x: 'x1', y: 'y1', z: 'z1' } // obj1= { x: 'x3', y: 'y1' } // obj2= { x: 'x3', y: 'y2' } // obj2= { y: 'y1', x: 'x3' }
如果作为函数的形参,会转化为数组,如:
function f(...args){ console.log('args is:', args) } f('name','kkkk') // args is: [ 'name', 'kkkk' ]
5.import和require的区别
1. require可以在代码的任何地方,而import只能用到文件的头部。
2.require是commonJs规范,import是es6规范。
3.CommonJS模块默认export的是一个对象,即使导出的是基础数据类型
4.require赋值功能,import是编译功能,所有import的性能要优于require。
5.当import遇到了default,于require是是完全不同的两种概念。
6.建议require使路径用绝对路径,import使用相对路径。
6.变量结构赋值
交换变量的值:
let x = 1; let y = 2; [x,y] = [y,x] //代码交换变量x和变量y的值,这样的写法不仅简洁,易读,语义非常清晰