Although ES6 has not yet been released, there are already programs rewritten in ES6, and various proposals for ES789 have already begun. Can you believe it? Trends are not something that we and the public can catch up with.
Although the trend is too fast, if we don’t stop the pace of learning, we will not be left behind by the trend. Let’s take a look at the new features in ES6, a new generation of JS.
Arrow Operator
If you know C# or Java, you must know lambda expressions. The new arrow operator => in ES6 has the same purpose. It simplifies writing functions. The left side of the operator is the input parameters, and the right side is the operation performed and the returned value Inputs=>outputs.
We know that callbacks are common in JS, and generally callbacks appear in the form of anonymous functions. It is necessary to write a function every time, which is very cumbersome. When the arrow operator is introduced, callbacks can be easily written. Please see the example below.
var array = [1, 2, 3]; //传统写法 array.forEach(function(v, i, a) { console.log(v); }); //ES6 array.forEach(v = > console.log(v));
You can open the traceur online code translation page mentioned at the beginning of the article and enter the code to see the effect.
class support
ES6 added support for classes and introduced the class keyword (in fact, class has always been a reserved word in JavaScript, the purpose is to consider that it may be used in new versions in the future, and now it finally comes in handy) . JS itself is object-oriented, and the classes provided in ES6 are actually just wrappers for the JS prototype pattern. Now that native class support is provided, object creation and inheritance are more intuitive, and concepts such as parent class method invocation, instantiation, static methods, and constructors are more visual.
The following code shows the use of classes in ES6. Again, you can paste the code into traceur to see the results yourself.
//类的定义 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();//输出 ‘My name is dummy' wayou.sayName();//输出 ‘My name is wayou' wayou.program();//输出 ‘I'm coding...'
Enhanced object literals
Object literals have been enhanced, the writing method is more concise and flexible, and more things can be done when defining objects. Specifically shown in:
In this way, object literals are more consistent with the class concept mentioned above, making it easier and more convenient to write object-oriented JavaScript.
//通过对象字面量创建对象 var human = { breathe() { console.log('breathing...'); } }; var worker = { __proto__: human, //设置此对象的原型为human,相当于继承human company: 'freelancer', work() { console.log('working...'); } }; human.breathe();//输出 ‘breathing...' //调用继承来的breathe方法 worker.breathe();//输出 ‘breathing...'
String template
String templates are relatively simple and easy to understand. ES6 allows the use of backticks ` to create strings. The string created in this way can contain variables ${vraible} wrapped in dollar signs and curly brackets. If you have used a back-end strongly typed language such as C#, you should be familiar with this feature.
//产生一个随机数 var num=Math.random(); //将这个数字输出到console console.log(`your num is ${num}`);
Deconstruction
Automatically parse values in arrays or objects. For example, if a function wants to return multiple values, the conventional approach is to return an object and return each value as a property of the object. But in ES6, using the feature of destructuring, you can directly return an array, and then the values in the array will be automatically parsed into the corresponding variable that receives the value.
var [x,y]=getVal(),//函数返回值的解构 [name,,age]=['wayou','male','secrect'];//数组解构 function getVal() { return [ 1, 2 ]; } console.log('x:'+x+', y:'+y);//输出:x:1, y:2 console.log('name:'+name+', age:'+age);//输出: name:wayou, age:secrect
Parameter default value, variable parameter, extended parameter
1. Default parameter value
You can now specify the default values of parameters when defining a function, instead of using the logical OR operator as before.
function sayHello(name){ //传统的指定默认参数的方式 var name=name||'dude'; console.log('Hello '+name); } //运用ES6的默认参数 function sayHello2(name='dude'){ console.log(`Hello ${name}`); } sayHello();//输出:Hello dude sayHello('Wayou');//输出:Hello Wayou sayHello2();//输出:Hello dude sayHello2('Wayou');//输出:Hello Wayou
2. Indefinite parameters
Indefinite parameters are the use of named parameters in a function while receiving an indefinite number of unnamed parameters. This is just syntactic sugar, and in previous JavaScript code we could achieve this through the arguments variable. The format of the variable parameters is three periods followed by the variable names representing all variable parameters. For example, in the following example,...x represents all parameters passed into the add function.
//将所有参数相加的函数 function add(...x){ return x.reduce((m,n)=>m+n); } //传递任意个数的参数 console.log(add(1,2,3));//输出:6 console.log(add(1,2,3,4,5));//输出:15
3. Expansion parameters
Extended parameters are another form of syntax sugar, which allows passing arrays or array-like parameters directly as function parameters without going through apply.
var people=['Wayou','John','Sherlock']; //sayHello函数本来接收三个单独的参数人妖,人二和人三 function sayHello(people1,people2,people3){ console.log(`Hello ${people1},${people2},${people3}`); } //但是我们将一个数组以拓展参数的形式传递,它能很好地映射到每个单独的参数 sayHello(...people);//输出:Hello Wayou,John,Sherlock //而在以前,如果需要传递数组当参数,我们需要使用函数的apply方法 sayHello.apply(null,people);//输出:Hello Wayou,John,Sherlock
let and const keywords
You can think of let as var, except that the variables it defines can only be used within a specific scope, and are invalid outside this scope. const is very intuitive and is used to define constants, that is, variables whose values cannot be changed.
for (let i=0;i<2;i++)console.log(i);//输出: 0,1 console.log(i);//输出:undefined,严格模式下会报错
for of value traversal
We all know that the for in loop is used to traverse arrays, array-like or objects. The newly introduced for of loop in ES6 has similar functions. The difference is that each time it loops, it provides not a serial number but a value.
var someArray = [ "a", "b", "c" ]; for (v of someArray) { console.log(v);//输出 a,b,c }
注意,此功能google traceur并未实现,所以无法模拟调试,下面有些功能也是如此
iterator, generator
这一部分的内容有点生涩,详情可以参见这里。以下是些基本概念。
模块
在ES6标准中,JavaScript原生支持module了。这种将JS代码分割成不同功能的小块进行模块化的概念是在一些三方规范中流行起来的,比如CommonJS和AMD模式。
将不同功能的代码分别写在不同文件中,各模块只需导出公共接口部分,然后通过模块的导入的方式可以在其他地方使用。下面的例子来自tutsplus:
// point.js module "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
// Sets var s = new Set(); s.add("hello").add("goodbye").add("hello"); s.size === 2; s.has("hello") === true; // Maps var m = new Map(); m.set("hello", 42); m.set(s, 34); m.get(s) == 34;
有时候我们会把对象作为一个对象的键用来存放属性值,普通集合类型比如简单对象会阻止垃圾回收器对这些作为属性键存在的对象的回收,有造成内存泄漏的危险。而WeakMap,WeakSet则更加安全些,这些作为属性键的对象如果没有别的变量在引用它们,则会被回收释放掉,具体还看下面的例子。
正文代码来自es6feature
// Weak Maps var wm = new WeakMap(); wm.set(s, { extra: 42 }); wm.size === undefined // Weak Sets var ws = new WeakSet(); ws.add({ data: 42 });//因为添加到ws的这个临时对象没有其他变量引用它,所以ws不会保存它的值,也就是说这次添加其实没有意思
Proxies
Proxy可以监听对象身上发生了什么事情,并在这些事情发生后执行一些相应的操作。一下子让我们对一个对象有了很强的追踪能力,同时在数据绑定方面也很有用处。
以下例子借用自这里。
//定义被侦听的目标对象 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.EPSILON Number.isInteger(Infinity) // false Number.isNaN("NaN") // false Math.acosh(3) // 1.762747174039086 Math.hypot(3, 4) // 5 Math.imul(Math.pow(2, 32) - 1, Math.pow(2, 32) - 2) // 2 "abcde".contains("cd") // true "abc".repeat(3) // "abcabcabc" Array.from(document.querySelectorAll('*')) // Returns a real Array Array.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", "c" Object.assign(Point, { origin: new Point(0,0) })
Promises
Promises是处理异步操作的一种模式,之前在很多三方库中有实现,比如jQuery的deferred 对象。当你发起一个异步请求,并绑定了.when(), .done()等事件处理程序时,其实就是在应用promise模式。
//创建promise var 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" });
The summary is just one sentence. The difference between the front and back ends is getting smaller and smaller. This article is based on lukehoban/es6features and also refers to a lot of blog information. The purpose of the editor is to help everyone better understand the latest standard of JavaScript, ECMAScript. 6. I hope it will be helpful to everyone’s study.