使用class来定义类
class Person{
}
class Person{
name:string="熏悟空";
age.number=1000;
}
const person = new Person();
console.log(person.name)
class Person{
static name:string="熏悟空";
age.number=1000;
}
console.log(Person.name)
class Person{
static name:string="熏悟空";
age.number=1000;
eat(){
console.log("吃桃子");
}
}
const person = new Person();
console.log(person.eat());
class Person{
static name:string="熏悟空";
age.number=1000;
static eat(){
console.log("吃桃子");
}
}
console.log(Person.eat());
使用constructor修饰,创建实例时调用
class Person{
name:string;
age.number;
constructor(name:string,age:number){
this.name = name;
this.age = age;
}
}
const person = new Person("熏悟空",1000);
console.log(person.name,person.age);
使用继承子类将会拥有父类的所有方法和属性
class Animal{
name:string;
age:number;
constructor(name:string,age:number){
console.log("构造函数")
this.name= name;
this.age= age;
}
sayHello(){
alert("动物在叫");
}
}
class Dog extends Animal{
sayHello(){
console.log("汪汪汪");
}
}
const dog = new Dog("旺财",3);
console.log(dog)
dog.sayHello()
需要注意,如果子类重写了构造方法,必须要使用super调用父类的构造方法
class Animal{
name:string;
constructor(name:string){
console.log("构造函数")
this.name= name;
}
sayHello(){
alert("动物在叫");
}
}
class Dog extends Animal{
age:number;
contructor(name:string,age:number){
super(name);
this.age = age;
}
sayHello(){
console.log("汪汪汪");
}
}
const dog = new Dog("旺财",3);
console.log(dog)
dog.sayHello()
使用abstract修饰的类是抽象类,
abstract class Animal{
name:string;
contructor(name:string){
this.name = name;
}
abtract sayHello():void;
}
使用interface修饰的类结构是接口,
interface MyInterface{
name:string;
sayHello():void;
}
class MyClass implements MyInterface{
constructor(name:string){
this.name = name;
}
sayHello(){
console.log("Hello");
}
}
class Person{
private name:string;
private age:number
constructor(name:string,age:number){
this.name = name;
this.age = age;
}
getName(){
return this.name;
}
setName(name:string){
this.name = name;
}
get _age(){
return this.age;
}
set _age(age:number){
this.age = age
}
}
const person = new Person("熏悟空",300);
person._age=360;
person.setName("沙和尚");
console.log(person._age);
注意
使用getter,setter 空格属性时需要注意以下两点
class Person{
constructor(public name:string,private age:number){
}
}
const person = new Person("小明",25);
console.log(person)