es6新特性:const与let变量、模板字面量、解构、增强的对象字面量、for...of循环、展开运算符(...)、剩余参数(可变参数)、es6箭头函数、类的支持、字符串模板、iterator、generator、模块、symbols等。
本教程操作环境:windows7系统、ecmascript 6版、dell g3电脑。
const 与 let 变量使用var带来的麻烦:
function getclothing(iscold) { if (iscold) { var freezing = 'grab a jacket!'; } else { var hot = 'it's a shorts kind of day.'; console.log(freezing); }}
运行getclothing(false)后输出的是undefined,这是因为执行function函数之前,所有变量都会被提升, 提升到函数作用域顶部.
let与const声明的变量解决了这种问题,因为他们是块级作用域, 在代码块(用{}表示)中使用let或const声明变量, 该变量会陷入暂时性死区直到该变量的声明被处理.
function getclothing(iscold) { if (iscold) { const freezing = 'grab a jacket!'; } else { const hot = 'it's a shorts kind of day.'; console.log(freezing); }}
运行getclothing(false)后输出的是referenceerror: freezing is not defined,因为 freezing 没有在 else 语句、函数作用域或全局作用域内声明,所以抛出 referenceerror。
关于使用let与const规则:
使用let声明的变量可以重新赋值,但是不能在同一作用域内重新声明使用const声明的变量必须赋值初始化,但是不能在同一作用域类重新声明也无法重新赋值.
【相关推荐:javascript视频教程】
模板字面量在es6之前,将字符串连接到一起的方法是+或者concat()方法,如
const student = { name: 'richard kalehoff', guardian: 'mr. kalehoff'};const teacher = { name: 'mrs. wilson', room: 'n231'}let message = student.name + ' please see ' + teacher.name + ' in ' + teacher.room + ' to pick up your report card.';
模板字面量本质上是包含嵌入式表达式的字符串字面量.
模板字面量用倒引号 ( `` )(而不是单引号 ( '' ) 或双引号( ))表示,可以包含用 ${expression} 表示的占位符
let message = `${student.name} please see ${teacher.name} in ${teacher.room} to pick up your report card.`;
解构在es6中,可以使用解构从数组和对象提取值并赋值给独特的变量
解构数组的值:
const point = [10, 25, -34];const [x, y, z] = point;console.log(x, y, z);
prints: 10 25 -34
[]表示被解构的数组, x,y,z表示要将数组中的值存储在其中的变量, 在解构数组是, 还可以忽略值, 例如const[x,,z]=point,忽略y坐标.
解构对象中的值:
const gemstone = { type: 'quartz', color: 'rose', karat: 21.29};const {type, color, karat} = gemstone;console.log(type, color, karat);
花括号 { } 表示被解构的对象,type、color 和 karat 表示要将对象中的属性存储到其中的变量
对象字面量简写法let type = 'quartz';let color = 'rose';let carat = 21.29;const gemstone = { type: type, color: color, carat: carat};console.log(gemstone);
使用和所分配的变量名称相同的名称初始化对象时如果属性名称和所分配的变量名称一样,那么就可以从对象属性中删掉这些重复的变量名称。
let type = 'quartz';let color = 'rose';let carat = 21.29;const gemstone = {type,color,carat};console.log(gemstone);
简写方法的名称:
const gemstone = { type, color, carat, calculateworth: function() { // 将根据类型(type),颜色(color)和克拉(carat)计算宝石(gemstone)的价值 }};
匿名函数被分配给属性 calculateworth,但是真的需要 function 关键字吗?在 es6 中不需要!
let gemstone = { type, color, carat, calculateworth() { ... }};
for...of循环for...of循环是最新添加到 javascript 循环系列中的循环。
它结合了其兄弟循环形式 for 循环和 for...in 循环的优势,可以循环任何可迭代(也就是遵守可迭代协议)类型的数据。默认情况下,包含以下数据类型:string、array、map 和 set,注意不包含 object 数据类型(即 {})。默认情况下,对象不可迭代。
for循环
const digits = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];for (let i = 0; i < digits.length; i++) { console.log(digits[i]);}
for 循环的最大缺点是需要跟踪计数器和退出条件。
虽然 for 循环在循环数组时的确具有优势,但是某些数据结构不是数组,因此并非始终适合使用 loop 循环。
for...in循环
const digits = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];for (const index in digits) { console.log(digits[index]);}
依然需要使用 index 来访问数组的值
当你需要向数组中添加额外的方法(或另一个对象)时,for...in 循环会带来很大的麻烦。因为 for...in 循环循环访问所有可枚举的属性,意味着如果向数组的原型中添加任何其他属性,这些属性也会出现在循环中。
array.prototype.decimalfy = function() { for (let i = 0; i < this.length; i++) { this[i] = this[i].tofixed(2); }};const digits = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];for (const index in digits) { console.log(digits[index]);}
foreach 循环 是另一种形式的 javascript 循环。但是,foreach() 实际上是数组方法,因此只能用在数组中。也无法停止或退出 foreach 循环。如果希望你的循环中出现这种行为,则需要使用基本的 for 循环。
for...of循环
for...of 循环用于循环访问任何可迭代的数据类型。
for...of 循环的编写方式和 for...in 循环的基本一样,只是将 in 替换为 of,可以忽略索引。
const digits = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];for (const digit of digits) { console.log(digit);}
建议使用复数对象名称来表示多个值的集合。这样,循环该集合时,可以使用名称的单数版本来表示集合中的单个值。例如,for (const button of buttons) {…}。
for...of 循环还具有其他优势,解决了 for 和 for...in 循环的不足之处。你可以随时停止或退出 for...of 循环。
for (const digit of digits) { if (digit % 2 === 0) { continue; } console.log(digit);}
不用担心向对象中添加新的属性。for...of 循环将只循环访问对象中的值。
array.prototype.decimalfy = function() { for (i = 0; i < this.length; i++) { this[i] = this[i].tofixed(2); }};const digits = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];for (const digit of digits) { console.log(digit);}
展开运算符展开运算符(用三个连续的点 (...) 表示)是 es6 中的新概念,使你能够将字面量对象展开为多个元素
const books = ["don quixote", "the hobbit", "alice in wonderland", "tale of two cities"];console.log(...books);
prints: don quixote the hobbit alice in wonderland tale of two cities
展开运算符的一个用途是结合数组。
如果你需要结合多个数组,在有展开运算符之前,必须使用 array的 concat() 方法。
const fruits = ["apples", "bananas", "pears"];const vegetables = ["corn", "potatoes", "carrots"];const produce = fruits.concat(vegetables);console.log(produce);
prints: ["apples", "bananas", "pears", "corn", "potatoes", "carrots"]
使用展开符来结合数组
const fruits = ["apples", "bananas", "pears"];const vegetables = ["corn", "potatoes", "carrots"];const produce = [...fruits,...vegetables];console.log(produce);
剩余参数(可变参数)使用展开运算符将数组展开为多个元素, 使用剩余参数可以将多个元素绑定到一个数组中.
剩余参数也用三个连续的点 ( ... ) 表示,使你能够将不定数量的元素表示为数组.
用途1: 将变量赋数组值时:
const order = [20.17, 18.67, 1.50, "cheese", "eggs", "milk", "bread"];const [total, subtotal, tax, ...items] = order;console.log(total, subtotal, tax, items);
用途2: 可变参数函数
对于参数不固定的函数,es6之前是使用参数对象(arguments)处理:
function sum() { let total = 0; for(const argument of arguments) { total += argument; } return total;}
在es6中使用剩余参数运算符则更为简洁,可读性提高:
function sum(...nums) { let total = 0; for(const num of nums) { total += num; } return total;}
es6箭头函数es6之前,使用普通函数把其中每个名字转换为大写形式:
const upperizednames = ['farrin', 'kagure', 'asser'].map(function(name) { return name.touppercase();});
箭头函数表示:
const upperizednames = ['farrin', 'kagure', 'asser'].map( name => name.touppercase());
普通函数可以是函数声明或者函数表达式, 但是箭头函数始终都是表达式, 全程是箭头函数表达式, 因此因此仅在表达式有效时才能使用,包括:
存储在变量中,当做参数传递给函数,存储在对象的属性中。const greet = name => `hello ${name}!`;
可以如下调用:
greet('asser');
如果函数的参数只有一个,不需要使用()包起来,但是只有一个或者多个, 则必须需要将参数列表放在圆括号内:
// 空参数列表需要括号const sayhi = () => console.log('hello udacity student!');// 多个参数需要括号const ordericecream = (flavor, cone) => console.log(`here's your ${flavor} ice cream in a ${cone} cone.`);ordericecream('chocolate', 'waffle');
一般箭头函数都只有一个表达式作为函数主题:
const upperizednames = ['farrin', 'kagure', 'asser'].map( name => name.touppercase());
这种函数表达式形式称为简写主体语法:
在函数主体周围没有花括号,自动返回表达式但是如果箭头函数的主体内需要多行代码, 则需要使用常规主体语法:
它将函数主体放在花括号内需要使用 return 语句来返回内容。const upperizednames = ['farrin', 'kagure', 'asser'].map( name => { name = name.touppercase(); return `${name} has ${name.length} characters in their name`;});
javascript标准函数this1、new 对象
const mysundae = new sundae('chocolate', ['sprinkles', 'hot fudge']);
sundae这个构造函数内的this的值是实例对象, 因为他使用new被调用.
2、指定的对象
const result = obj1.printname.call(obj2);
函数使用call/apply被调用,this的值指向指定的obj2,因为call()第一个参数明确设置this的指向
3、上下`文对象
data.teleport();
函数是对象的方法, this指向就是那个对象,此处this就是指向data.
4、全局对象或 undefined
teleport();
此处是this指向全局对象,在严格模式下,指向undefined.
javascript中this是很复杂的概念, 要详细判断this,请参考this豁然开朗
箭头函数和this对于普通函数, this的值基于函数如何被调用, 对于箭头函数,this的值基于函数周围的上下文, 换句话说,this的值和函数外面的this的值是一样的.
function icecream() { this.scoops = 0;}// 为 icecream 添加 addscoop 方法icecream.prototype.addscoop = function() { settimeout(function() { this.scoops++; console.log('scoop added!'); console.log(this.scoops); // undefined+1=nan console.log(dessert.scoops); //0 }, 500);};
标题
const dessert = new icecream();
dessert.addscoop();
传递给 settimeout() 的函数被调用时没用到 new、call() 或 apply(),也没用到上下文对象。意味着函数内的 this 的值是全局对象,不是 dessert 对象。实际上发生的情况是,创建了新的 scoops 变量(默认值为 undefined),然后递增(undefined + 1 结果为 nan);
解决此问题的方式之一是使用闭包(closure):
// 构造函数function icecream() { this.scoops = 0;}// 为 icecream 添加 addscoop 方法icecream.prototype.addscoop = function() { const cone = this; // 设置 `this` 给 `cone`变量 settimeout(function() { cone.scoops++; // 引用`cone`变量 console.log('scoop added!'); console.log(dessert.scoops);//1 }, 0.5);};const dessert = new icecream();dessert.addscoop();
箭头函数的作用正是如此, 将settimeout()的函数改为剪头函数:
// 构造函数function icecream() { this.scoops = 0;}// 为 icecream 添加 addscoop 方法icecream.prototype.addscoop = function() { settimeout(() => { // 一个箭头函数被传递给settimeout this.scoops++; console.log('scoop added!'); console.log(dessert.scoops);//1 }, 0.5);};const dessert = new icecream();dessert.addscoop();
默认参数函数function greet(name, greeting) { name = (typeof name !== 'undefined') ? name : 'student'; greeting = (typeof greeting !== 'undefined') ? greeting : 'welcome'; return `${greeting} ${name}!`;}greet(); // welcome student!greet('james'); // welcome james!greet('richard', 'howdy'); // howdy richard!
greet() 函数中混乱的前两行的作用是什么?它们的作用是当所需的参数未提供时,为函数提供默认的值。但是看起来很麻烦, es6引入一种新的方式创建默认值, 他叫默认函数参数:
function greet(name = 'student', greeting = 'welcome') { return `${greeting} ${name}!`;}greet(); // welcome student!greet('james'); // welcome james!greet('richard', 'howdy'); // howdy richard!
默认值与解构1、默认值与解构数组
function creategrid([width = 5, height = 5]) { return `generates a ${width} x ${height} grid`;}
creategrid([]); // generates a 5 x 5 grid
creategrid([2]); // generates a 2 x 5 grid
creategrid([2, 3]); // generates a 2 x 3 grid
creategrid([undefined, 3]); // generates a 5 x 3 grid
creategrid() 函数预期传入的是数组。它通过解构将数组中的第一项设为 width,第二项设为 height。如果数组为空,或者只有一项,那么就会使用默认参数,并将缺失的参数设为默认值 5。
但是存在一个问题:
creategrid(); // throws an error
uncaught typeerror: cannot read property 'symbol(symbol.iterator)' of undefined
出现错误,因为 creategrid() 预期传入的是数组,然后对其进行解构。因为函数被调用时没有传入数组,所以出现问题。但是,我们可以使用默认的函数参数!
function creategrid([width = 5, height = 5] = []) { return `generating a grid of ${width} by ${height}`;}creategrid(); // generates a 5 x 5 grid
returns: generates a 5 x 5 grid
2、默认值与解构函数
就像使用数组默认值解构数组一样,函数可以让对象成为一个默认参数,并使用对象解构:
function createsundae({scoops = 1, toppings = ['hot fudge']}={}) { const scooptext = scoops === 1 ? 'scoop' : 'scoops'; return `your sundae has ${scoops} ${scooptext} with ${toppings.join(' and ')} toppings.`;}createsundae({}); // your sundae has 1 scoop with hot fudge toppings.createsundae({scoops: 2}); // your sundae has 2 scoops with hot fudge toppings.createsundae({scoops: 2, toppings: ['sprinkles']}); // your sundae has 2 scoops with sprinkles toppings.createsundae({toppings: ['cookie dough']}); // your sundae has 1 scoop with cookie dough toppings.createsundae(); // your sundae has 1 scoop with hot fudge toppings.
3、数组默认值与对象默认值
默认函数参数只是个简单的添加内容,但是却带来很多便利!与数组默认值相比,对象默认值具备的一个优势是能够处理跳过的选项。看看下面的代码:
function createsundae({scoops = 1, toppings = ['hot fudge']} = {}) { … }
在 createsundae() 函数使用对象默认值进行解构时,如果你想使用 scoops 的默认值,但是更改 toppings,那么只需使用 toppings 传入一个对象:
createsundae({toppings: ['hot fudge', 'sprinkles', 'caramel']});
将上述示例与使用数组默认值进行解构的同一函数相对比。
function createsundae([scoops = 1, toppings = ['hot fudge']] = []) { … }
对于这个函数,如果想使用 scoops 的默认数量,但是更改 toppings,则必须以这种奇怪的方式调用你的函数:
createsundae([undefined, ['hot fudge', 'sprinkles', 'caramel']]);
因为数组是基于位置的,我们需要传入 undefined 以跳过第一个参数(并使用默认值)来到达第二个参数。
javascript类es5创建类:
function plane(numengines) { this.numengines = numengines; this.enginesactive = false;}// 由所有实例 继承 的方法plane.prototype.startengines = function () { console.log('starting engines...'); this.enginesactive = true;};
es6类只是一个语法糖,原型继续实际上在底层隐藏起来, 与传统类机制语言有些区别.
class plane { //constructor方法虽然在类中,但不是原型上的方法,只是用来生成实例的. constructor(numengines) { this.numengines = numengines; this.enginesactive = false; } //原型上的方法, 由所有实例对象共享. startengines() { console.log('starting engines…'); this.enginesactive = true; }}console.log(typeof plane); //function
javascript中类其实只是function, 方法之间不能使用,,不用逗号区分属性和方法.
静态方法
要添加静态方法,请在方法名称前面加上关键字 static
class plane { constructor(numengines) { this.numengines = numengines; this.enginesactive = false; } static badweather(planes) { for (plane of planes) { plane.enginesactive = false; } } startengines() { console.log('starting engines…'); this.enginesactive = true; }}
关键字class带来其他基于类的语言的很多思想,但是没有向javascript中添加此功能javascript类实际上还是原型继承创建javascript类的新实例时必须使用new关键字super 和 extends使用新的super和extends关键字扩展类:
class tree { constructor(size = '10', leaves = {spring: 'green', summer: 'green', fall: 'orange', winter: null}) { this.size = size; this.leaves = leaves; this.leafcolor = null; } changeseason(season) { this.leafcolor = this.leaves[season]; if (season === 'spring') { this.size += 1; } }}class maple extends tree { constructor(syrupqty = 15, size, leaves) { super(size, leaves); //super用作函数 this.syrupqty = syrupqty; } changeseason(season) { super.changeseason(season);//super用作对象 if (season === 'spring') { this.syrupqty += 1; } } gathersyrup() { this.syrupqty -= 3; }}
使用es5编写同样功能的类:
function tree(size, leaves) { this.size = size || 10; this.leaves = leaves || {spring: 'green', summer: 'green', fall: 'orange', winter: null}; this.leafcolor;}tree.prototype.changeseason = function(season) { this.leafcolor = this.leaves[season]; if (season === 'spring') { this.size += 1; }}function maple (syrupqty, size, leaves) { tree.call(this, size, leaves); this.syrupqty = syrupqty || 15;}maple.prototype = object.create(tree.prototype);maple.prototype.constructor = maple;maple.prototype.changeseason = function(season) { tree.prototype.changeseason.call(this, season); if (season === 'spring') { this.syrupqty += 1; }}maple.prototype.gathersyrup = function() { this.syrupqty -= 3;}
super 必须在 this 之前被调用
在子类构造函数中,在使用 this 之前,必须先调用超级类。
class apple {}class grannysmith extends apple { constructor(tartnesslevel, energy) { this.tartnesslevel = tartnesslevel; // 在 'super' 之前会抛出一个错误! super(energy); }}
字符串模板字符串模板相对简单易懂些。es6中允许使用反引号 ` 来创建字符串,此种方法创建的字符串里面可以包含由美元符号加花括号包裹的变量${vraible}。如果你使用过像c#等后端强类型语言的话,对此功能应该不会陌生。
//产生一个随机数var num=math.random();//将这个数字输出到consoleconsole.log(`your num is ${num}`);
iterator, generator这一部分的内容有点生涩,详情可以参见这里。以下是些基本概念。
iterator:它是这么一个对象,拥有一个next方法,这个方法返回一个对象{done,value},这个对象包含两个属性,一个布尔类型的done和包含任意值的valueiterable: 这是这么一个对象,拥有一个obj[@@iterator]方法,这个方法返回一个iteratorgenerator: 它是一种特殊的iterator。反的next方法可以接收一个参数并且返回值取决与它的构造函数(generator function)。generator同时拥有一个throw方法generator 函数: 即generator的构造函数。此函数内可以使用yield关键字。在yield出现的地方可以通过generator的next或throw方法向外界传递值。generator 函数是通过function*来声明的yield 关键字:它可以暂停函数的执行,随后可以再进进入函数继续执行模块在es6标准中,javascript原生支持module了。这种将js代码分割成不同功能的小块进行模块化的概念是在一些三方规范中流行起来的,比如commonjs和amd模式。
将不同功能的代码分别写在不同文件中,各模块只需导出公共接口部分,然后通过模块的导入的方式可以在其他地方使用。下面的例子来自tutsplus:
// point.jsmodule point { export class point { constructor (x, y) { public x = x; public y = y; } }} // myapp.js//声明引用的模块module point from /point.js;//这里可以看出,尽管声明了引用的模块,还是可以通过指定需要的部分进行导入import point from point; var origin = new point(0, 0);console.log(origin);
map,set 和 weakmap,weakset这些是新加的集合类型,提供了更加方便的获取属性值的方法,不用像以前一样用hasownproperty来检查某个属性是属于原型链上的呢还是当前对象的。同时,在进行属性值添加与获取时有专门的get,set 方法。
下方代码来自es6feature
// setsvar s = new set();s.add(hello).add(goodbye).add(hello);s.size === 2;s.has(hello) === true;// mapsvar m = new map();m.set(hello, 42);m.set(s, 34);m.get(s) == 34;
有时候我们会把对象作为一个对象的键用来存放属性值,普通集合类型比如简单对象会阻止垃圾回收器对这些作为属性键存在的对象的回收,有造成内存泄漏的危险。而weakmap,weakset则更加安全些,这些作为属性键的对象如果没有别的变量在引用它们,则会被回收释放掉,具体还看下面的例子。
正文代码来自es6feature
// weak mapsvar wm = new weakmap();wm.set(s, { extra: 42 });wm.size === undefined// weak setsvar ws = new weakset();ws.add({ data: 42 });//因为添加到ws的这个临时对象没有其他变量引用它,所以ws不会保存它的值,也就是说这次添加其实没有意思
proxiesproxy可以监听对象身上发生了什么事情,并在这些事情发生后执行一些相应的操作。一下子让我们对一个对象有了很强的追踪能力,同时在数据绑定方面也很有用处。
以下例子借用自这里。
//定义被侦听的目标对象var engineer = { name: 'joe sixpack', salary: 50 };//定义处理程序var interceptor = { set: function (receiver, property, value) { console.log(property, 'is changed to', value); receiver[property] = value; }};//创建代理以进行侦听engineer = proxy(engineer, interceptor);//做一些改动来触发代理engineer.salary = 60;//控制台输出:salary is changed to 60
上面代码我已加了注释,这里进一步解释。对于处理程序,是在被侦听的对象身上发生了相应事件之后,处理程序里面的方法就会被调用,上面例子中我们设置了set的处理函数,表明,如果我们侦听的对象的属性被更改,也就是被set了,那这个处理程序就会被调用,同时通过参数能够得知是哪个属性被更改,更改为了什么值。
symbols我们知道对象其实是键值对的集合,而键通常来说是字符串。而现在除了字符串外,我们还可以用symbol这种值来做为对象的键。symbol是一种基本类型,像数字,字符串还有布尔一样,它不是一个对象。symbol 通过调用symbol函数产生,它接收一个可选的名字参数,该函数返回的symbol是唯一的。之后就可以用这个返回值做为对象的键了。symbol还可以用来创建私有属性,外部无法直接访问由symbol做为键的属性值。
以下例子来自es6features
(function() { // 创建symbol var key = symbol(key); function myclass(privatedata) { this[key] = privatedata; } myclass.prototype = { dostuff: function() { ... this[key] ... } };})();var c = new myclass(hello)c[key] === undefined//无法访问该属性,因为是私有的
math,number,string,object 的新api对math,number,string还有object等添加了许多新的api。下面代码同样来自es6features,对这些新api进行了简单展示。
number.epsilonnumber.isinteger(infinity) // falsenumber.isnan(nan) // falsemath.acosh(3) // 1.762747174039086math.hypot(3, 4) // 5math.imul(math.pow(2, 32) - 1, math.pow(2, 32) - 2) // 2abcde.contains(cd) // trueabc.repeat(3) // abcabcabcarray.from(document.queryselectorall('*')) // returns a real arrayarray.of(1, 2, 3) // similar to new array(...), but without special one-arg behavior[0, 0, 0].fill(7, 1) // [0,7,7][1,2,3].findindex(x => x == 2) // 1[a, b, c].entries() // iterator [0, a], [1,b], [2,c][a, b, c].keys() // iterator 0, 1, 2[a, b, c].values() // iterator a, b, cobject.assign(point, { origin: new point(0,0) })
promisespromises是处理异步操作的一种模式,之前在很多三方库中有实现,比如jquery的deferred 对象。当你发起一个异步请求,并绑定了.when(), .done()等事件处理程序时,其实就是在应用promise模式。
//创建promisevar promise = new promise(function(resolve, reject) { // 进行一些异步或耗时操作 if ( /*如果成功 */ ) { resolve(stuff worked!); } else { reject(error(it broke)); }});//绑定处理程序promise.then(function(result) { //promise成功的话会执行这里 console.log(result); // stuff worked!}, function(err) { //promise失败会执行这里 console.log(err); // error: it broke});
更多编程相关知识,请访问:编程视频!!
以上就是es6有哪些新特性的详细内容。