@Secretmm
2017-12-09T07:43:16.000000Z
字数 2313
阅读 848
好好学习
使用 class 定义类,使用 constructor 定义构造函数。
通过 new 生成新实例的时候,会自动调用构造函数。
class Animal {constructor(name) {this.name = name;}sayHi() {return `My name is ${this.name}`;}}let a = new Animal('Jack');console.log(a.sayHi()); // My name is Jack
用static关键字,修饰的方法或属性不依赖于实例,可以直接通过类名来访问在类内部和外部访问方式一样;【多用于比较独立的变量或者方法--因为该类的实例是调用不了静态变量或者静态方法的】
eg:
class Test() {static one: string;static getTest() {return 'test';}}//外面使用时let test = Test.one;let getTest = Test.getTest();
[看到说es6不存在私有属性和私有变量]?? 这里是ts,哈哈哈
修饰的属性或方法是私有的,不能在声明它的类的外部访问
修饰的属性或方法是公有的,可以在任何地方被访问到,默认所有的属性和方法都是 public。
protected 修饰的属性或方法是受保护的,它和 private 类似,区别是它在子类中也是允许被访问的
在“类”的内部可以使用get和set关键字,对某个属性设置存值函数和取值函数,拦截该属性的存取行为。
这里的拦截是什么意思呢?还有使用场景是什么?
eg:
class Platform {protected isAudioOn: boolean;constructor() {this.isAudioOn = false;}get audioOn() {return this.isAudioOn;}set audioOn(value) {this.isAudioOn = value;store.dispatch(value ? 'audioOpened' : 'audioClosed');}}
假如要实现一个功能,就是isAudioOn的值改变了之后,要执行store.dispatch(value ? 'audioOpened' : 'audioClosed'),可以这样做,设置isAuioOn为public属性,每当isAuioOn在改变的时候加上store.dispatch(value ? 'audioOpened' : 'audioClosed');
这样就很麻烦,因为store.dispath()要重复加。
此时就可以采用get和set关键字来拦截isAudioOn的修改;
如上例:
将isAudioOn包装成私有属性,外界通过设置audioOn的值,来修改isAudioOn的值;
let plat = new Platform();plat.audioOn = true;
执行该语句时,被set拦截,实际上执行的是
//value为true;set audioOn(value) {this.isAudioOn = value;store.dispatch(value ? 'audioOpened' : 'audioClosed');}
注意:
plat.audioOn = true;并不是在这里给audioOn赋值为true,实际上audioOn的值只等于get的返回值;在set中可以改变audioOn的值
eg:
class MyClass {constructor() {}get prop() {return 'getter';}set prop(value) {console.log('setter');}}let inst = new MyClass();function test() {inst.prop = '666';//被拦截,执行的是set prop('666'),打印出'setter'console.log(inst.prop); // 'getter'}
使用extends关键字实现继承,子类中使用super关键字来调用父类的构造函数和方法。
class Animal {constructor(name) {this.name = name;}sayHi() {return `My name is ${this.name}`;}}let a = new Animal('Jack');console.log(a.sayHi()); // My name is Jack
class Cat extends Animal {constructor(name) {super(name); // 调用父类的 constructor(name)console.log(this.name);}sayHi() {return 'Meow, ' + super.sayHi(); // 调用父类的 sayHi()}}let c = new Cat('Tom'); // Tomconsole.log(c.sayHi()); // Meow, My name is Tom
abstract 用于定义抽象类和其中的抽象方法
- 抽象类不允许被实例化
- 抽象类中的抽象方法必须被子类实现
abstract class Animal {public name;public constructor(name) {this.name = name;}public abstract sayHi();}class Cat extends Animal {public sayHi() {console.log(`Meow, My name is ${this.name}`);}}let cat = new Cat('Tom');