5 Star 66 Fork 13

韩旭明 / grammarLearning

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
08_Class_2、修饰符.ts 1.71 KB
一键复制 编辑 原始数据 按行查看 历史
韩旭明 提交于 2023-01-27 16:56 . 修改说明
/**
* 在 TypeScript 中能够为 Class 成员添加这些修饰符:
* public / private / protected / readonly。
*
* public / private / protected 三位都属于 访问性修饰符,
* 而 readonly 属于 操作性修饰符(就和 interface 中的 readonly 意义一致)。
*
* 通常不会为构造函数添加修饰符,让它保持默认的 public
* 当不显式使用访问性修饰符,成员的访问性默认会被标记为 public
*/
/**
* public:此类成员在类、类的实例、子类中都能被访问。
* private:此类成员仅能在类的内部被访问。
* protected:
* 此类成员仅能在类与子类中被访问,可以将 类 和 类的实例 当成两种概念,
* 即一旦实例化完毕(出厂零件),那就和类(工厂)没关系了,即不允许再访问受保护的成员。
*/
class Foo {
private prop: string;
constructor(inputProp: string) {
this.prop = inputProp;
}
protected print(addon: string): void {
console.log(`${this.prop} and ${addon}`)
}
public get propA(): string {
return `${this.prop}+A`;
}
public set propA(value: string) {
this.propA = `${value}+A`
}
}
/**
* 在上面的例子中,通过 构造函数 为 类成员赋值 的方式还是略显麻烦,需要声明 类属性 以及在 构造函数 中进行赋值。
* 简单起见,可以在 构造函数 中对参数应用 访问性修饰符:
*/
class FooA {
constructor(public arg1: string, private arg2: boolean) { }
}
let FooATest = new FooA("hanxuming", true)
console.log(FooATest.arg1) //hanxuming
console.log(FooATest.arg2)
//export {}:解决“无法重新声明块范围变量”错误提示问题
export { }
1
https://gitee.com/hanxuming/grammar-learning.git
git@gitee.com:hanxuming/grammar-learning.git
hanxuming
grammar-learning
grammarLearning
master

搜索帮助