class 语法糖总结
class Parent {
static parentName : 'parent'
static parentSay () {//静态方法
}
constructor(){
}
say () {
}
}
静态属性和静态方法
静态属性和方法只对class 有效
- 静态属性
class Parent {
static parentName : 'parent';
static parentSay (word) {//静态方法
console.log(word)
}
}
实例的属性和方法
实例的属性和方法,默认为public, 类和子类的实例都有效
- 实例方法
- 实例属性
私有属性和方法(私有方法和私有属性,是只能在类的内部访问的方法和属性,外部不能访问, es6中需要模拟来实现)
当成员被标记成 private时,它就不能在声明它的类的外部访问
//如 ts 中:
class Animal {
private name: string;
constructor(theName: string) { this.name = theName; }
}
new Animal("Cat").name; // 错误: 'name' 是私有的.
- 模拟实现
将私有方法移出模块,因为模块内部的所有方法都是对外可见的
class Widget {
foo (baz) {
bar.call(this, baz);
}
// ...
}
function bar(baz) {
return this.snaf = baz;
}
通过 Symbol 模拟私有属性和方法
class Fruit {
constructor () {
const number = Symbol('number')
class F {
constructor () {
this[number] = 1
}
getNumber () {
return this[number]
}
setNumber (num) {
this[number] = num
}
}
return new F()
}
}
const apple = new Fruit()
apple.getNumber() // 1
apple.setNumber(5)
apple.getNumber() // 5
apple[number] // Uncaught ReferenceError: number is not defined