js中的class

3 分钟
59 阅读
js中的class

让我解释 TypeScript 中 public 的用法:

  1. 基本用法
typescript 复制代码
class Jedi {
    public name: string;  // 公开属性
    public age: number;   // 公开属性

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

    public sayHello(): void {  // 公开方法
        console.log(`Hello, I'm ${this.name}`);
    }
}
  1. 访问修饰符对比
typescript 复制代码
class Jedi {
    public name: string;      // 公开的,任何地方都可以访问
    protected age: number;    // 受保护的,只能在类内部和子类中访问
    private id: string;       // 私有的,只能在类内部访问
}
  1. 默认行为
typescript 复制代码
class Jedi {
    name: string;  // 默认就是 public
    // 等同于
    public name: string;
}
  1. 在构造函数中使用
typescript 复制代码
class Jedi {
    // 简写方式,自动创建并初始化属性
    constructor(
        public name: string,
        public age: number
    ) {}
    // 等同于
    // public name: string;
    // public age: number;
    // constructor(name: string, age: number) {
    //     this.name = name;
    //     this.age = age;
    // }
}
  1. 在接口实现中使用
typescript 复制代码
interface IJedi {
    name: string;
    age: number;
}

class Jedi implements IJedi {
    public name: string;
    public age: number;
}
  1. 在继承中使用
typescript 复制代码
class Person {
    public name: string;
    protected age: number;
    private id: string;
}

class Jedi extends Person {
    public force: number;

    constructor(name: string, age: number, force: number) {
        super();
        this.name = name;     // 可以访问
        this.age = age;       // 可以访问
        // this.id = "123";   // 错误:不能访问私有属性
        this.force = force;
    }
}
  1. 在方法中使用
typescript 复制代码
class Jedi {
    public name: string;

    // 公开方法
    public sayHello(): void {
        console.log(`Hello, I'm ${this.name}`);
    }

    // 受保护方法
    protected meditate(): void {
        console.log("Meditating...");
    }

    // 私有方法
    private useForce(): void {
        console.log("Using the Force...");
    }
}
  1. 在静态成员中使用
typescript 复制代码
class Jedi {
    public static count: number = 0;  // 公开静态属性
    public static create(): Jedi {    // 公开静态方法
        return new Jedi();
    }
}
  1. 在 getter/setter 中使用
typescript 复制代码
class Jedi {
    private _name: string;

    public get name(): string {
        return this._name;
    }

    public set name(value: string) {
        this._name = value;
    }
}
  1. 在抽象类中使用
typescript 复制代码
abstract class ForceUser {
    public name: string;
    public abstract useForce(): void;  // 抽象方法必须是 public
}

主要特点:

  • public 是默认的访问修饰符
  • 可以在任何地方访问 public 成员
  • 子类可以继承和访问父类的 public 成员
  • 接口中的成员默认都是 public
  • 抽象类中的抽象方法必须是 public

使用建议:

  1. 优先使用 public 成员
  2. 只在需要限制访问时才使用 protected 或 private
  3. 使用 public 可以提高代码的可测试性和可维护性
  4. 在 API 设计中,public 成员是接口的一部分

评论

评论

发表评论