一、类
TS中的类是由class关键字开始的。那么什么是类呢·?
类是指用来创造一类对象的模板,而通过这个模板创建出来的对象叫做实例。
二、使用步骤
代码如下(示例):
class Animal {
color: string = 'black';
age: number = 0;
// 构造函数
constructor(color: string, age: number){
this.color = color;
this.age = age;
}
}
这是一个最简单的动物类了。在这类中我们需要注意:
- 类的名称首字母要大写
- 在typescript中,成员属性和方法都必须先声明
如何书写方法呢?
示例:
class Animal {
color: string = 'black';
age: number = 0;
// 构造函数
constructor(color: string, age: number){
this.color = color;
this.age = age;
}
say(){
alert('my color is' + this.color );
}
walk = ()=>{
console.log('walk....');
}
}
const ani = new Animal('yellow',10);
ani.say()
ani.walk()
我们可以直接在构造函数外面定义方法,然后通过new实例进行调用。