TS中的类
首先确认es5中的类
简单写一个类~
function fun(name,age){
this.name = name;
this.age = age;
this.run = function(){
console.log(111111)
}
}
let f = new fun();
f.run()
对象继承
function father(name,age){
this.name = name;
this.age = age;
this.run = function(){
console.log(111111)
}
}
let f = new father();
father.prototype.eat = function(){
console.log('i want meat!')
}
function son(){
father.call(this, 'zhangsan', 12);
}
son.prototype = father.prototype;
let s = new son();
类的类型
基本除声明变量类型外同es6及c#,声明在属性及方法上面
public公有
不举例子了~
protected保护类型
class Father{
protected name:string;
constructor(name:string){
this.name = name;
}
}
let f = new Father('mingzi');
alert(f.name);
private保护类型
class Father{
protected name:string;
constructor(name:string){
this.name = name;
}
}
class Son extends Father{
constructor(name:string){
super(name)
}
run(){
console.log(this.name)
}
}
let f = new Father('mingzi');
alert(f.name);
静态方法
function Father{
this.run = function(){
}
}
father.work = function(){
}
class Father{
protected name:string;
static dos = 1;
constructor(name:string){
this.name = name;
}
static work(){
console.log(1,Father.dos)
}
}
Father.work();
jQuery中的$是一个声明的对象;$直接点出来的就是静态方法
多态
父类定义一个方法不去实现,不同的子类重写这个方法去做不同的实现;就是多态(后有对于多态的拓展)
class Father{
name:string;
constructor(name:string){
this.name = name;
}
run(){
console.log(111111)
}
}
class Son1 extends Father{
constructor(){
}
run(){
console.log('son1')
}
}
class Son2 extends Father{
constructor(){
}
run(){
console.log('son2')
}
}
抽象类
抽象类和抽象方法用来定义标准;属于是多态的拓展;关键字abstract
abstract class Father{
name:string;
constructor(){
}
abstract run():any;
}
class Son1 extends Father{
run(){
console.log(111)
}
}
class Son2 extends Father{
run(){
console.log(2222)
}
}
如果实例化抽象类会报错;只能通过子类;abstr方法只能放在抽象类里面
如果父类constructor中有参数传入;子类中必须有对应得参数传入;