zoukankan      html  css  js  c++  java
  • 修饰符 public、 private 和 protected和区别

     

    TypeScript 可以使用三种访问修饰符(Access Modifiers),分别是 public、private 和 protected。

    • public 修饰的属性或方法是公有的,可以在任何地方被访问到,默认所有的属性和方法都是 public 的
    • private 修饰的属性或方法是私有的,不能在声明它的类的外部访问
    • protected 修饰的属性或方法是受保护的,它和 private 类似,区别是它在子类中也是允许被访问的

    下面举一些例子:

    class Animal {
      public name;
      public constructor(name) {
        this.name = name;
      }
    }
     
    let a = new Animal('Jack');
    console.log(a.name); // Jack
    a.name = 'Tom';
    console.log(a.name); // Tom

    上面的例子中,name 被设置为了 public,所以直接访问实例的 name 属性是允许的。

    很多时候,我们希望有的属性是无法直接存取的,这时候就可以用 private 了:

    class Animal {
      private name;
      public constructor(name) {
        this.name = name;
      }
    }
     
    let a = new Animal('Jack');
    console.log(a.name); // Jack
    a.name = 'Tom';
     
    // index.ts(9,13): error TS2341: Property 'name' is private and only accessible within class 'Animal'.
    // index.ts(10,1): error TS2341: Property 'name' is private and only accessible within class 'Animal'.

    需要注意的是,TypeScript 编译之后的代码中,并没有限制 private 属性在外部的可访问性。

    上面的例子编译后的代码是:

    var Animal = (function () {
        function Animal(name) {
            this.name = name;
        }
        return Animal;
    }());
    var a = new Animal('Jack');
    console.log(a.name);
    a.name = 'Tom';

    使用 private 修饰的属性或方法,在子类中也是不允许访问的:

    class Animal {
      private name;
      public constructor(name) {
        this.name = name;
      }
    }
     
    class Cat extends Animal {
      constructor(name) {
        super(name);
        console.log(this.name);
      }
    }
     
    // index.ts(11,17): error TS2341: Property 'name' is private and only accessible within class 'Animal'.
     



    而如果是用 protected 修饰,则允许在子类中访问:

    class Animal {
      protected name;
      public constructor(name) {
        this.name = name;
      }
    }
     
    class Cat extends Animal {
      constructor(name) {
        super(name);
        console.log(this.name);
      }
    }
     
  • 相关阅读:
    Python3 input() 函数
    Python3 enumerate() 函数
    Python3 ascii() 函数
    Python3 sorted() 函数
    css sprite
    Java 理论与实践: 并发集合类
    关于 Java Collections API 您不知道的 5 件事,第 1 部分
    Treasure! Free Mobile Design Resources
    Indigo Studio
    ionic:Build mobile apps faster with the web technologies you know and love
  • 原文地址:https://www.cnblogs.com/flxy-1028/p/10959711.html
Copyright © 2011-2022 走看看