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



})()
posted @ 2021-10-07 17:16  前端那点事  阅读(474)  评论(0编辑  收藏  举报