1、箭头函数,直接写出来v =>看不出来什么,但是跟传统写法一比较,很直观地就能看出v =>是代替了匿名函数 function(v)的写法,{}与逻辑照旧,但是要注意,=与>之间不能有空格.
IDEA只需要改一下framework环境就好,默认是ES5.1
var arr = [1,2,3]; arr.forEach(function(v){
console.log(v);
alert(v);
}); //ES6
arr.forEach(v => {
console.log(v);
alert(v);
});
2、class类的支持,js已经向高级语言靠拢了,这种写法简单易读,比原型链继承通俗易懂
class Animal{
constructor(name){
this.name = name;
}
sayName(){
alert('my name is ' + this.name);
}
} class Person extends Animal{
constructor(name){
//调用父类构造
super(name);
}
program(){
alert('coding...');
}
} var an = new Animal('rab'),
ren = new Person('ren');
an.sayName();// alert('my name is rab')
ren.sayName();// alert('my name is ren')
ren.program();// alert('coding...')
3、增强的对象字面量
这么说不好理解,其实就是
- 可以在对象字面量里面定义原型
- 定义方法可以不用function关键字
- 直接调用父类方法
var human = { breathe(){ alert('human breathing...'); } }; var worker = { __proto__: human,// 此处,通过直接指向原型链实现继承 company: 'com', work(){ alert('worker is working'); } }; human.breathe();// human breathing... worker.breathe();// human breathing...
4、字符串模板
ES6中允许使用反引号 ` 来创建字符串(注意,什么是反引号?就是ESC下面,Tab上面那个键,从此告别 ‘++’...)
var num = Math.random();
alert(`your num is ${num}`);
特点一:字符串可换行
var s = `In JavaScript this is
not legal.`; console.log(s);
// In JavaScript this is
// not legal.
特点二:模板嵌套——可用于循环挂数据
const tmpl = addrs => `
<table>
${addrs.map(addr => `
<tr><td>${addr.first}</td></tr>
<tr><td>${addr.last}</td></tr>
`).join('')}
</table>
`; const data = [
{ first: '<Jane>', last: 'Bond'},
{ first: 'Lars', last: '<Croft>'}
]; console.log(tmpl(data));
// <table>
// <tr><td><Jane></td></tr>
// <tr><td>Bond</td></tr>
// <tr><td>Lars</td></tr>
// <tr><td><Croft></td></tr>
// </table>
特点三:可用于动态生成代码变成可执行函数
let str = "return" + "`Hello ${name}!`";
let func = new Function("name", str);
console.log(func("jack"));// Hello jack!
let str = "(name) => `Hello ${name}!`";
let func = eval.call(null, str);
console.log(func("jack"));// Hello jack!
特点四:可用于过滤恶意代码
function SaferHTML(templateData) {
var s;
for (var i = 0; i < arguments.length; i++) {
var arg = String(arguments[i]); s += arg.replace(/<script>/g, "<script>")
.replace(/<\/script>/g, "</script>");
}
return s;
}
var sender = '<script>alert("abc")</script>'; // 恶意代码
var message = SaferHTML`<p>${sender} has sent you a message.</p>`; console.log(message);//<p><script>alert("abc")</script> has sent you a message.</p>
展望:ES7即将加入位数“0”补全函数
var num = "1"; console.log(num.padStart(10,"0")); //
5、解构
啥是解构,,大白话就是,数组取值不用下标了,给事先定义一些key,通过key来取数组里对应的value
var [x,y] = getVal(),
[name,,age] = ['nam','female','18'];//此处,没有给第二个sex定义key function getVal() {
//此处,不能省略function关键字..说明只有在定义一个类对象时才可以省略..
return [ 1, 2 ];
}
//此处,模板写法是否很眼熟呢~
alert(`x:${x}, y:${y}`);// x:1, y:2
alert(`name:${name}, age:${age}`);// name:nam, age:18
try{
alert(`name:${name}, sex:${sex}, age:${age}`);
}
catch (e){
console.error(e.message);// sex is not defined
}
解构的用途:
(1)函数多个返回值:
//数组形式
function test() {
return [1,2,3];
}
var [a,b,c] = test();
//a==1
//b==2
//c==3 //对象形式
function test2() {
return {
fir:1,
sec:2
};
}
var { fir, sec } = test2();
//fir==1
//sec==2
(2)函数参数定义:
//有序传参
function test1([x,y,z]){}
test1([1,2,3]); //无序传参
function test2({x,y,z}){}
test2({y:3, x:9, z:1}) //无序默认值
function request(url,{
async = true,
headers = { 'Content-Type': 'application/json' },
method = 'GET'
}){
return [url, async, headers, method];
}
let [u, a, h, m] = request('/api/post.php',{method:'POST', headers:{'Content-Type': 'application/xml'}});
//u == '/api/post.php'
//a == true
//h == {'Content-Type': 'application/xml'}
//m == 'POST'
(3)提取json数据:
var json = {
id: 7,
state: "isOk",
list:[4,90]
};
let {id, state, list: data} = json;
console.log(id, state, data);
//7 isOk [ 4, 90 ]
(4)遍历对象key-value
var map = new Map();
map.set('k1','v1');
map.set('k2','v2'); for(let [key,value] of map){
console.log(key + ':' + value);
}
//k1:v1
//k2:v2 for(let [key] of map){
console.log(key);
}
//k1
//k2 for(let [,value] of map){
console.log(value);
}
//v1
//v2
(5)获取对象方法
var obj = {
sourceFunc:function () {
return "I'm sourceFunc";
},
paramsFunc: function (par1) {
return "I'm paramsFunc. par1 is " + par1;
}
} const {paramsFunc, sourceFunc} = obj;
//paramsFunc('参数1') == "I'm paramsFunc. par1 is 参数1"
//sourceFunc() == "I'm sourceFunc"
6、参数的各种玩法
6.1参数默认值,熟悉C#的同学一定不陌生了,函数参数默认值的这种写法(照这个趋势..以后大家都得是全栈工程师..)
function Say(msg){
//传统指定参数默认值
var msg = msg || 'message';
alert('nihao ' + msg);
} //ES6
function Say2(msg = '我不好'){
alert(`nihao ${msg}`);
} Say();// nihao message
Say2();// nihao 我不好
Say('WOHENHAO');// nihao WOHENHAO
Say2('你不好也得好');// nihao 你不好也得好
6.2不定参数,这个我在C#上没有见过(也可能是我孤陋寡闻了..)
//传统写法
var arr = [1,2,3,4] function add(m,n){
return m + n;
} alert(arr.reduce(add, 2));// 此处,结果为12,给了一个起始值2,2 + 1 + 2 + 3 + 4 = 12 //ES6
function add2(...x){
return x.reduce((m,n) => m+n);
} alert(add2(1,2,3,4));//
alert(add2(12,14));//
6.3拓展参数,个人理解也是多参映射的一种偷懒写法
var peoples = ['zhang','wang','li','zhao']; function hello(p1,p2,p3,p4) {
console.log(`hello ${p1} ${p2} ${p3} ${p4}`);
}
//将数组以拓展参数的形式传递,它能很好地映射到每个单独的参数
hello(...peoples);// hello zhang wang li zhao
7、for of循环【对比for in循环】
var arr = ['a','b','c']
var obj = { 'a':'aa', 'b':'bb', 'c': 'cc'}
function obj2(){
this.a = 'b';
this.c = 'd';
} for(var v in arr)
{
console.log(v);// 0 1 2
}
for(var v in obj)
{
console.log(v);// a b c
}
for(var v in obj2)
{
console.log(v);// 啥也输不出
} for(v of arr)
{
console.log(v);// a b c
}
for(v of obj)
{
console.log(v);// TypeError: obj is not iterable
}
for(v of obj2)
{
console.log(v);// TypeError: obj2 is not iterable
}
结论一:for in循环可以遍历数组与对象,但不能遍历值类型对象,只能遍历引用类型对象
结论二:for of循环只能遍历数组等一些继承了Iterator接口的对象
本文只是参考学习大神的博客做的笔记,并非原创哈~【http://www.cnblogs.com/Wayou/p/es6_new_features.html】