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();