ts中類的屬性的封裝


ts中類的屬性的封裝

 


(function(){
    /* 
        public 修飾的屬性可以在任意位置訪問(修改)默認值
        private :私有屬性,私有屬性只能在類的內部進行訪問
                - 通過在類中添加方法使得私有屬性可以被外部訪問

        protected 受保護的屬性,只能在當前類的子類中訪問(修改)
    */

    class Person {
        private _name :string;
        private _age :number;

        constructor(name:string,age:number){
            this._name = name
            this._age = age
        }

        /* 
        getter方法用來讀取屬性
        setter方法用來設置屬性
        */

        get name(){
            return this._name
        }

        set name(value){
            this.name = value
        }

        get age(){
            return this._age
        }

        set age(value){
            if(value >0){
                console.log('age合法');
            }

            this._age = value
        }

    }

    let per = new Person("張三",18);
    per.age =10
    // console.log(per.age);

    class A {
        protected num:number

        constructor(num){
            this.num = num 
        }
    }

    class B extends A {

        test(){
            
            console.log(this.num);
        }
    }

    const b = new B(10);
    b.test()



})()


免責聲明!

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



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