最近刚接触ES6,把基础语法整理一番。
1、常量
const PI = 3.1415926
console.log(PI)
2、作用域
{
function foo() {
return 1
}
console.log("foo()===1", foo() === 1)
{
function foo() {
return 2
}
console.log("foo()===2", foo() === 2)
}
console.log("foo()===1", foo() === 1)
}
3、箭头函数
{
let evens = [1, 2, 3, 4, 5];
let odds = evens.map(v => v + 1);
console.log(evens, odds);
}
{
var factory = function() {
this.a = 'a';
this.b = 'b';
this.c = {
a: 'a+',
b: () => {
return this.a
}
}
}
console.log(new factory().c.b());//输出a
}
4、默认参数
{
function f(x, y = 7, z = 42) {
return x + y + z
}
console.log(f(1, 3));//输出46
}
{
function checkParameter() {
throw new Error('can\'t be empty')
}
function f(x = checkParameter(), y = 7, z = 42) {
return x + y + z
}
console.log(f(1));
try {
f()
} catch (e) {
console.log(e);//输出50
} finally {}
}
{
// ES6 可变参数
function f(...a) {
var sum = 0;
a.forEach(item => {
sum += item * 1
});
return sum
}
console.log(f(1, 2, 3, 6));//输出12
}
{
// ES6 利用扩展运算符合并数组
var params = ['hello', true, 7];
var other = [
1, 2, ...params
];
console.log(other);//输出(5) [1, 2, "hello", true, 7]
}
5、对象代理
{
// ES6
let Person = {
name: 'es6',
sex: 'male',
age: 15
};
let person = new Proxy(Person, {
get(target, key) {
return target[key]
},
set(target,key,value){
if(key!=='sex'){
target[key]=value;
}
}
});
console.table({
name:person.name,//es6
sex:person.sex,//male
age:person.age//15
});
try {
person.sex='female';
} catch (e) {
console.log(e);
} finally {
}
}