TS创建类的写法:
/*
class OrderDetail{
goodsName: string;
price: number;
count: number;
constructor(goodsName_: string, price_: number, count_: number ){
this.goodsName = goodsName_;
this.price = price_;
this.count = count_;
}
}
// ts 类构造器赋值 新赋值方式
class Order{
orderId: string;
date: Date;
customer: string;
phone: string;
orderDetailArray: Array<OrderDetail> = [];
constructor(orderId_: string, date_: Date, customer_: string, phone_: string, orderDetailArray_: Array<OrderDetail>){
this.orderId = orderId_;
this.date = date_;
this.customer = customer_;
this.phone =phone_;
this.orderDetailArray =orderDetailArray_
}
}
let order = new Order('2022020201', new Date(), 'zhangssan', '13265868978',[{goodsName:'鼠标', price:20, count:5},{goodsName:'主机', price:200, count:3}]);
console.log('order: ',order)
*/
// 构造函数直接为参数添加 public, 此时参数就变成了一个属性,默认构造函数就会给这个属性赋值(隐士操作) 以上代码改写如下:
class OrderDetail{
constructor(public goodsName: string, public price: number, public count: number ){ }
}
// ts 类构造器赋值 新赋值方式
class Order{
constructor(public orderId_: string, public date_: Date, public customer_: string, public phone_: string, public orderDetailArray_: Array<OrderDetail>){
}
}
let order = new Order('2022020201', new Date(), 'zhangssan', '13265868978',[{ goodsName:'鼠标', price:20, count:5},{goodsName:'主机', price:200, count:3}]);
console.log('order: ',order)
采用TS定义类和ES6定义类的区别:
1. 定义方式取的区别:
方式 1:先在类中定义属性然后在构造函数中通过 this 赋值;
方式 2:构造函数直接为参数增加 public,给构造器的参数如果加上 public,这个参数就变成了一个属性, 默认构造函数会给这个属性赋值 [隐式操作], 可以省去很多代码
ES6 依然沿袭了 JavaScript 赋值的方式,在构造函数直接 this 来定义属性并赋值:
class Order {
constructor(orderId, date, custname, phone, orderDetailArray) {
this.orderId = orderId;
this.date = date;
this.custname = custname;
this.phone = phone;
this.orderDetailArray = orderDetailArray;
}
}
2. ES6 类没有访问修饰符,TS 类自带访问修饰符
ES6 类暂时还没有访问修饰符【public protected private】这也让 ES6 类设置访问权限变的异常麻烦,即使借助 call 方法或者 symbol 类型设置了访问权限局限性也很大,其实也并没有真正彻底解决访问权限的问题。这点让 ES6 类在项目中对属性和方法的权限控制很受限制。 TS 类却自带 public protected private 三种访问权限,设置访问权限轻松自如。【不设置默认访问权限为 public 】 理解访问修饰符很简单,后面我们讲解完继承后再讲解,大家很快会理解。
3. TS 类是静态类型语言的类,而 ES6 类按照 JavaScript 的一个语法标准设计而成
TS 是静态类型语言,具有类型注解和类型推导的能力,项目上线后隐藏语法和类型错误的的风险几乎为零,而 ES6 是 JavaScript 的一个语法标准,没有数据类型检查的能力