1. class Dog{
  2. name = "name1";
  3. age = 3;
  4. bark(){
  5. alert('bark');
  6. }
  7. }
  8. const dog = new Dog;
  9. const dog1 = new Dog;
  10. const dog2 = new Dog;

这样出来调用的属性是一样的
但是想要实现调用的类是不同的,加入构造函数constructor

constructor

被称为构造函数,会在对象创建时调用

class Dog{
    name:string;
    age :number;

    constructor(name:string,age:number){
        // 在实例方法中,this就表示当前的实例
        // 在构造函数中当前对象就是当前新建的那个对象
        // 可以通过this向新建的对象中添加属性
        this.name = name;
        this.age = age;

    }
    bark(){
        // 在方法中可以通过this来表示当前调用方法的对象
        console.log(this);

    }
}
const dog = new Dog('dog1',5);
const dog1 = new Dog('dog2',8);