class Dog {
// 需要先定义,才能在constructor中this指向
name: string;
age: number;
// 构造函数,会在对象创建时调用
// new Dog() 的时候,就会调用constructor
constructor(name:string, age:number) {
/**
* 在实例方法中,this就表示当前的实例
* 在构造函数中当前对象就是当前新建的那个对象
* 可以通过this指向新建的对象中添加属性
*/
this.name = name;
this.age = age;
}
bark(){
console.log(this.name + " is barking, woofing ")
}
}
const dog = new Dog('Tom', 4);
console.log(dog);
const dog2 = new Dog('Max', 2);
console.log(dog2);
dog2.bark();
class Dog {
// 需要先定义,才能在constructor中this指向
name: string;
age: number;
// 构造函数,会在对象创建时调用
// new Dog() 的时候,就会调用constructor
constructor(name:string, age:number) {
/**
* 在实例方法中,this就表示当前的实例
* 在构造函数中当前对象就是当前新建的那个对象
* 可以通过this指向新建的对象中添加属性
*/
this.name = name;
this.age = age;
}
bark(){
console.log(this.name + " is barking, woofing ")
}
}
const dog = new Dog('Tom', 4);
console.log(dog);
const dog2 = new Dog('Max', 2);
console.log(dog2);
dog2.bark();