ES6相关的新特性(2015)
- 类class:
新建一个js/ts文件,可以在这个Class中的构造函数进行初始化以及方法的封装,然后导出这个类。
export class Product {
name: any;
constructor(name:any) {
this.name = name;
}
getProduct() {
console.log('产品的名称打印: ',this.name);
}
}
import { Product } from "./product";
const proName = 'iphone';
let pro = new Product(proName);
pro.getProduct();
- 模块化(ES Module)
ES Module导出(模块中的常量、变量、函数或者类),只要在声明前加上export关键字即可,ES Module自动采用严格模式,忽略 'use strict'。
function onAddCount(_total: any,_count: any) {
return _total+_count;
}
function onMinusCount(_total: any,_count: any) {
return _total-_count;
}
export { onAddCount, onMinusCount}
import { onAddCount } from "./product";
onAddCount(100,10)
- 箭头函数:
需要注意的是this本身是没有this指向的。
const func = (a,b) => a + b;
func(1,2); // 3
- 函数参数默认值:
onDealData(total = this.total, )
当调用该方法不加参数时,默认的传入前面定好的数据,如果在调用的时候传入了参数,那么就按照传入的参数计算数据。
export class DefaultComponent implements OnInit {
total = 100;
ngOnInit(): void {
}
ngAfterViewInit(): void {
// 不传参数
console.log(this.onDealData()); // 80
// 不传参数
console.log(this.onDealData(150)); // 130
}
onDealData(total = this.total, ) {
let count = 20;
return total-count;
}
}
- 模板字符串:
const name = 'test';
const str = `模板字符串${name}`;
解构赋值:
let a = 1,b=2;
[a,b] = [b,a];
console.log(a,b);
《深入理解ES6》书中提到过一个点是解构赋值最需要注意的,比如下面的代码:
var {a=1,b=2} ={b:undefined};
console.log(a,b); // 1 2
可以看到当值为undefined的时候,传入的还是默认值,那么默认值在什么情况下失效呢,在传入的值为null时,便不会使用默认值了。
var {a=1,b=2} ={b:null};
console.log(a,b); // 1 null
还需要注意的是,如果是参数省略,那么一样是使用的默认值
var [c=3,d=4] =[,undefined];
console.log(c,d); // 3 4
- 拓展运算符:
let arr = [1,2,3,4,5];
let temp = ['a','b','c'];
console.log([...temp,...arr]);
- 对象属性简写:
const name = 'a';
const obj = { name }
- Promise对象:
Promise 对象是由关键字 new 及其构造函数来创建的。该构造函数会把一个叫做“处理器函数”(executor function)的函数作为它的参数。这个“处理器函数”接受两个函数——resolve 和 reject ——作为其参数。当异步任务顺利完成且返回结果值时,会调用 resolve 函数;而当异步任务失败且返回失败原因(通常是一个错误对象)时,会调用reject 函数。
Promise对象存在两种状态:
待定(pending): 初始状态,既没有被兑现,也没有被拒绝。
已兑现(fulfilled): 意味着操作成功完成。
已拒绝(rejected): 意味着操作失败。
Promise需要注意的是:不可能实现直接将 Promise.then 中的值 return 出来
。只能先return 出 Promise 对象,然后在 .then 的执行体中处理异步请求得到的值(或者去使用 async/await)
export class DefaultComponent implements OnInit {
isCollapsed: any;
total = 100;
ngOnInit(): void {
}
ngAfterViewInit(): void {
this.onDealData().then(value => console.log(value)); // 80
}
onDealData(total = this.total, isLoading = true) {
let count = 20;
return new Promise((resolve,reject)=>{
if(isLoading){
resolve(total-count)
}else{
reject()
}
})
}
}
- let、const:
let、const需要注意相同点以及不同点:
相同点:
1.块级作用域,块之外访问会报错
2.不能变量提升,在声明之前访问会报错
3.不允许在同一快中重复声明(let,const一样)
不同点:
1.变量与常量的区别
同时最需要注意的是“暂时性死区”,也就是所声明的变量或者常量会与当前的区域绑定起来,不会受外部影响
ngAfterViewInit(): void {
var count = 10;
for (let i = 0; i < 2; i++) {
console.log(count);
let count = 1;
console.log('count:',count,'i:',i);
}
}

由于let声明的变量不存在变量提升,因此,当在该作用域内打印count,不会获取到外部的count变量,而是拿的当前作用域内的count。这就是暂时性死区。
网友评论