// 抽象类
/**
* 1. 抽象类可以具体实现,也可以定义抽象方法
* 2.方法修饰符
* public 共有的 任何地方都可以访问到
* private 私有的 不能在类的外部使用,只能在内部使用
* protected 受保护的 子类中可以使用
*/
abstract class Animate {
abstract makeSound(): void;
protected move(): void {
console.log('动物移动了');
}
}
// 类既可以是实体类,也可以是个类型
class Dog extends Animate {
#region: string;
constructor() {
super()
this.#region = '庄子'
}
makeSound(): void {
console.log('汪汪汪');
}
private uname: string = "于谦"
}
const dog: Dog = new Dog()
console.log((dog as any).region);
dog.move()
dog.makeSound()
class Demo {
#num: number
constructor() {
this.#num = 32
}
}
const s = new Demo
console.log(s.num);
在这里 需要在 tsconfig.ts 中设置 lib:es2015 以上 才能使用 # 内部私有变量
在类中使用私有属性时 严格意义上通过这种方式
class Demo {
#num: number
constructor() {
this.#num = 32
}
}
const s = new Demo
console.log(s.num);
执行 tsc 编译之后将会是是以下结果
var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
if (kind === "m") throw new TypeError("Private method is not writable");
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
};
var _Demo_num;
// 注意,编译之后这里将使用的是 WeakMap 来存储私有变量
var Demo = /** @class */ (function () {
function Demo() {
_Demo_num.set(this, void 0);
__classPrivateFieldSet(this, _Demo_num, 32, "f");
}
return Demo;
}());
_Demo_num = new WeakMap();
var s = new Demo;
console.log(s.num);
当使用 private 定义私有属性时,
class Demo {
private num: number
constructor() {
this.num = 32
}
}
const s = new Demo
console.log(s.num);
编译将会是
故而通过这种方式定义私有,实际上很容易被修改到