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