class Person {
// 属性
name: string;
age: number;
// 构造函数
constructor(name:string, age:number) {
this.name = name;
this.age = age;
}
// 方法
print() {
console.log('name: ' + this.name + ' age: ' + this.age);
}
}
var p = new Person('Joh', 90);
p.print();
class Human {
name: string;
age: number;
tell() {
return this.name + ' ' + this.age;
}
}
// Student 继承自 Human
class Student extends Human {
school: string;
// 此处Student 也必须传递构造方法
tell() {
return this.name + ' ' + this.age + ' ' + this.school;
}
}
var s = new Student();
s.name = 'Joh';
s.age = 90;
s.school = 'MIT';
console.log(s.tell());
使用super关键字继承属性
class Human {
name: string;
age: number;
constructor(name: string, age:number) {
this.name = name;
this.age = age;
}
tell() {
return this.name + ' ' + this.age;
}
}
// Student 继承自 Human
class Student extends Human {
school: string;
// 此处Student 也必须传递构造方法
constructor(school: string) {
this.school = school;
super('Joh', 90);
}
tell() {
return this.name + ' ' + this.age + ' ' + this.school;
}
}
var ss = new Student('MIT');
console.log(s.tell());
在ts中有两种访问修饰符:
- public : 共有的
- private : 私有的
class People {
// public 是默认的, 不加修饰符都是public
public name:string;
age:number;
// private 无法访问和继承
private color:string;
getInfo() {
return this.name + ':' + this.age;
}
}
class Teacher extends People {
school:string;
getInfo() {
return this.name + ':' + this.age + ':' + this.school;
}
}
var t = new Teacher();
t.name = 'Joh';
t.age = '90';
t.school = 'MIT';
console.log(t.getInfo());
在constructor中也可添加修饰符
class People {
// 如下所示
constructor(public height: number){
}
}
-
在默认情况下,如果不添加访问修饰符,那么声明的属性或方法都是共有的,即:public
-
上述 Teacher 继承自 People,继承了所有public的属性和方法
-
如果将上述name添加
private
修饰符,那么编译就会报错,因为private声明的属性不会被继承
class People {
public height:number;
private weight:number;
size:number;
constructor(private name:string, public age:number, color:string) {
this.name = name;
this.age = age;
this.color = color;
}
print() {
return this.name + " : " + this.age;
}
public say() {
console.log('people say!');
}
private pee() {
console.log('people pee!');
}
}
以上是不同的几种设置访问修饰符的方式
- 如果不写的话,那么就是public的
- 访问修饰符可出现在constructor中
通过 getter 和 setter 方法来设置
class Hello {
name:string;
// 私有的 _age属性
private _age:number;
// 普通方法
tell() {
return this.name;
}
// getter 和 setter 来访问和设置私有方法, 为外部提供一个接口来使用
get name():string{
return this._name;
}
set name(n:string){
this._name = n;
}
}
var h = new Hello():
h.name = 'Joh';
console.log(h.tell());
class Person {
name:string;
// 静态属性或方法 需要使用类名来调用
static age:string;
tell() {
alert('Name: ' + this.name);
}
getInfo() {
return 'Name: ' + this.name + ' ' + 'Age' + this.age;
}
}
var p = new Person();
p.name = 'Joh';
Person.age = 90;
p.tell();
console.log(p.getInfo());
class Greeter {
greeting:string;
constructor(message: string) {
this.greeting = message;
}
greet() {
return 'Hello, ' + this.greeting;
}
}
var gr:Greeter; // 此处声明gr为Greeter的类型
gr = new Greeter(); // 此处实例化赋值
console.log(gr.greet('Joh'));