class static,public,protected,private

103 阅读1分钟
static
    只能在Per内使用,也只能是Per使用
    class Per{
        static name:1;
        static getName(){
            age = '我是'+this.name
        }
    }
    Per.name 
    Per.getName()
    
ts public 公共属性和方法 默认为公共属性和方法
ts private
    不能被类外边和此类的子类所访问
    class Per{
        privat name:1;
         getName(){}
    }
    console.log(Per.name)
    let p1 = new Per()
    console.log(p1.name) // error
    
    class PerChild extends Per{
       constructor(){
           super()
       }
    }
    console.log(PerChild.name)
    
    
    class getGTong {
        name: string;
        constructor(name: any) {
            this.name = name;
        }
    }
    class Child extends getGTong {
        constructor() {
            super('heihei');
        }
    }
    class Other {
        private name: string;
        constructor(name: any) {
            this.name = name;
        }
    }
    let tong = new getGTong('hahah');
    let child = new Child();
    let other = new Other('hhhh');
    tong = child;
    tong = other; //报错 不能将类型“Other”分配给类型“getGTong”。 
    属性“name”在类型“Other”中是私有属性,但在类型“getGTong”中不是。
ts protected ## 受保护的修饰符
      //声明一个类
    class getGTong {
        protected name: string;
        constructor(name: any) {
            this.name = name;
        }
    }
    class Child extends getGTong {
        constructor() {
            super('heihei');
            console.log(this.name); //可以访问基类受保护的成员
        }
    }

    let tong = new getGTong('hahah');
    let child = new Child();
    console.log(child.name); //报错 属性“name”受保护,只能在类“getGTong”及其子类中访问。