typeScript 之 (7) 构造函数和this

构造函数和this
class Dog 
{
  name:string
  age:number
  //constructor 被称为构造函数
  // 构造函数会在对象创建时调用
  // 通过构造函数赋值
  constructor(name:string,age:number){
    //在实例方法中,this就表示当前的实例
    //在构造函数中当前对象就是当前新建的那个对象
    //可以通过this向新建的对象中添加属性

    this.name = name
    this.age =age
    
  }

  bark(){
    console.log(this.name)
  }
}

const dog  = new Dog("张三",18)
const dog1  = new Dog("张三1",18)
console.log(dog)
console.log(dog1);

 

posted @ 2021-05-10 09:17  zmztyas  阅读(273)  评论(0编辑  收藏  举报