虽然说期待之后世界不再变幻莫测,但现在确实是在变化最大的时候,客户端和前端在因为有react和诸多限制之后再慢慢统一,不管最后统一的如何,也意味着工种在变得越来越和谐,好像不再需要那么多的人。我希望我能在这变化中做争取做那个不变的人。
最早接触语法糖的时候是写coffeeScript的时候,那段时光还是真的挺美好的,创业的激情总是让人感觉不到疲惫。现在EC6出了各种语法糖。写起来感觉也是不错的。
二进制和八进制表示法
前缀0b和0o分别表示二进制和八进制数值的新的写法。
0b111110111 === 503
0o767 === 503
增强的对象写法
'use strict'
let birth = 1,
Person = {
name: '张三',
birth,
hello() {
console.log('我的名字是', this.name);
}
};
console.log(Person) // { name: '张三', birth: 1, hello: [Function: hello] }
箭头函数
一般的写法,下面写了一些例子。值得注意的是箭头函数中的this,this是当前环境下上面一层的this,并不是调用方的this
'use strict'
var f = () => 5;
// 等同于
var f = function() {
return 5
};
var sum = (num1, num2) => num1 + num2;
// 等同于
var sum = (num1, num2) => {
return num1 + num2;
}
// 等同于
var sum = function(num1, num2) {
return num1 + num2;
};
// 正常函数写法
[1, 2, 3].map(function(x) {
return x * x;
});
// 箭头函数写法
[1, 2, 3].map(x => x * x);
export与import
在以前js代码之间要进行文件拆分都依赖AMD或者CMD.现在EC6提供类似的方法引入.暴露通过export
// 最基础的方式
// text.js
let name = "karyn";
let getName = () => {
return name + 'song';
}
export { name, getName };
// index.js
import { name, getName } from './text.js';
console.log(name); // karyn
console.log(getName()) // karynsong
// 使用 AS 的别名方式
// text.js
let _getxxx = () => {
return 'karynsong'
}
export { _getxxx as getxxx };
// index.js
import { getxxx as getName } from './text.js';
console.log(getName()) // aaa
// export 多个方法分散在文件中的多个地方
// text.js
export let name = 'karyn';
export let age = 22;
export function Info(){
return name + age
}
// index.js
import { name, age, Info } from './text.js';
console.log(name, age) // karyn 22
console.log(Info()) // karyn22
// export default,一个文件可以 default 出多个 function 或者 class,但引入只有一个
// text.js
export let name = 'karyn';
export default function area(radius) {
return Math.PI * radius * radius;
}
export default function circumference(radius) {
return 2 * Math.PI * radius;
}
// index.js
// 下面这种引用可以引用到其中一个 default 方法,及其他的非 default 方法
import area, { name } from './text.js';
console.log("圆面积:" + area(4));
// 或者这样写 下面这种引用可以引用到其中一个 default 方法,及其他的非 default 方法
// import circumference, { name } from './text.js';
// console.log("圆周长:" + circumference(14));
console.log(name);