Type Script类
定义类
class Person{
name:string;
age:nubmer;
constructor(name:string,age:number){
this.name=name;
this.age=age;
}
run():void{
console.log(this.name,this.age);
}
//Setting and Getting方法
getName(): string {
return this.name;
}
setName(name: string): void {
this.name = name;
}
getAge(): number {
return this.age;
}
setAge(age: number): void {
this.age = age;
}
}
//----------test-------------
let person = new Person("卑微的自己", 1213);
person.setName('肖杰斌');
person.setAge(12);
person.run();
实现继承
//父类
class People {
name: string;
constructor(name: string) {
this.name = name;
}
run(): string {
console.log(this.name);
return this.name;
}
}
//子类继承
class Biological extends People{
constructor(name:string){
super(name);
}
}
// --------------test--------------
let biological = new Biological("讨好你~");
biological.run();
修饰符
在类里面的修饰符拥有三种
- public:共有 类里面和外面多可以访问
- protected:保护类型 在类里面,子类里面多可以访问,类外部无法访问
- private:私有 在类里面可以访问,类外部无法访问
属性如果不加修饰符,默认就是公有的.
//父类
class Car{
public name: string;
protected color: string;
private price: number;
constructor(name:string,color:string,price:number){
this.name=name;
this.color=color;
this.price=price;
}
}
//------------------- tset -----------
console.log(car.name);
console.log(car.color);//错误
console.log(car.price);//错误
//子类
class Tool extends Car {
constructor(name: string, color: string, price: number) {
super(name, color, price);
}
run(): void {
console.log(this.name);
console.log(this.color);
console.log(this.price);//错误
}
}
// ------------- test -------------
let tool = new Tool('劳斯莱斯', '红色的', 100000000);
console.log(tool.name);
console.log(tool.color);//错误
console.log(tool.price);//错误
tool.run();
模块
let dbUrl = 'xxxxx';
//方式一:
export let username='xiaojiebn';
let getDataValue = (): any[] => {
console.log('获取数据库的数据1111');
return [{ title: '123' }, { title: 'xiaojiebin' }]
}
let save = (): boolean => {
console.log('保存成功');
return true;
}
//方式二:
//export defaul dbUrl;
//方式三:
export { getDataValue, save, dbUrl }
//-------------test-------------
import { getDataValue, save, dbUrl } from './db';
getDataValue();
save();
console.log(dbUrl);
命名空间
//每个命名空间多是独立的,命名不会影响
export namespace a {
export class dog<T>{
name: string;
constructor(name: string) {
this.name = name;
}
eat() {
console.log(this.name + '在吃狗粮~');
}
}
}
export namespace b {
export class cat<T>{
name: string;
constructor(name: string) {
this.name = name;
}
eat() {
console.log(this.name + '再吃喵粮~');
}
}
}
import { a, b } from './animal'
let dog = new a.dog('小禹');
dog.eat();
let cat = new b.cat('you');
cat.eat();