TypeScript - 構造函數 constructor


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 {
// 需要先定義,才能在constructorthis指向
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();


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM