1 类型
1.1 参数属性
参数属性通过给构造器函数参数前面添加一个访问限定符来声明。使用private限定一个参数属性会声明并初始化一个私有成员,对于public和protected来说也是一样的。
class C0 {
readonly p1: string;
constructor(p1: string) {
this.p1 = p1
}
}
let c0 = new C0("hello C0");
// c0.p1 = "新值"; // 报错 readonly
class C1 {
constructor(readonly p1: string) {
}
} // p1等价于C0的p1
class C3 {
constructor(private p1: string, protected p2: number, public p3: string) {
}
}
// p1,p2,p3等价于C4里的属性
class C4 {
private p1: string;
protected p2: number;
public p3: string;
constructor(p1: string, p2: number, p3: string) {
this.p1 = p1;
this.p2 = p2;
this.p3 = p3;
}
}
1.2 存取器
Typescript支持通过getters/setters来截取对对象成员的访问。它能帮助你有效的控制对对象成员的访问。 (存取器要求你将编译器设置为输出ECMAScript 5或更高)
class Person {
private _age: number;
get age(): number {
return this._age;
}
set age(newAge) {
if(newAge <= 0) {
console.log("Error: 年龄不合法")
return
}
this._age = newAge;
}
}
let person = new Person();
person.age = 0; // Error: 年龄不合法
console.log(person.age); //undefined
只带有get不带有set的存储器自动被推断为readonly。
1.3 类与接口的区别
1.3.1 接口
一般用来定义数据结构,可以充当一些model对象的基类使用;
接口只声明成员方法,不做实现;
1.3.2 类
类声明并实现方法;
2 函数
2.1 箭头函数
2.1.1 this指向
箭头函数体内的this对象,就是定义时所在的对象,而不是使用时所在的对象。this对象的指向是固定的。this 关键字始终表示定义箭头函数的对象。
let fun = function () {
console.log("常规函数 this:" + this)
}
document.getElementById("btn").addEventListener("click",fun)//常规函数 this:[object HTMLButtonElement]
let fun1 = () => {
console.log("箭头函数 this:" + this)
}
document.getElementById("btn1").addEventListener("click",fun1)//箭头函数 this:[object Window]
2.1.2 不适用场所
1)作为构造函数,或者箭头函数定义一个方法需要绑定到对象时;
2)定义事件回调函数需要使用this时;
3)使用arguments对象(函数参数数组对象)时(箭头函数没有arguments这个对象);
2.2 this 参数
this参数是一个假的参数,它出现在参数列表的最前面。
function fun (this: void) {}//表示在函数内不能使用this
class Rectangle {
constructor(private width,private height) {
}
fun(this: void) {//禁止在方法中使用this
}
getArea() {
return () => {//this 为 any类型
return this.width * this.height;
}
}
getArea2(this: Rectangle) {
return () => { //this 为 Rectangle类型
return this.width * this.height;
}
}
}
let rec = new Rectangle(2,5);
let getArea = rec.getArea();
console.log(getArea());
let getArea2 = rec.getArea2();
console.log(getArea2())
3 泛型
3.1 泛型约束
定义一个接口来描述约束条件。使用这个接口和extends关键字来实现约束:
interface Lengthwise {
length: number;
}
function loggingIdentity<T extends Lengthwise>(arg: T){
console.log(arg.length);
}
console.log(loggingIdentity({length: 24})); //24