静态方法
学习的视频当中用jQuery中$函数封装原理解释了下静态方法的使用记录下 理解多少算多少
function $(element) {
return new Base(element)
}
function Base(element) {
this.element = element // 获取的dom节点
this.css=function (arttr,value) {
this.element.style.arttr = value
}
}
$.get = function(url){
....
}
$('#box').css() //实例方法
$.get(url,function () { // 静态方法
})
typescript中的静态方法 static关键字
class Person {
name:string;
age:number = 18
static sex = "男" //静态属性
constructor(name:string,age:number) {
this.name=name
}
run():void{
console.log(this.name+"在运动")
}
static getName():void{ // 静态方法 如果静态方法只能使用静态属性
console.log('静态方法',this.age) //undefined
console.log('静态方法',this.sex) // 男
}
}
// 静态方法调用
Person.getName()
继承多态
父类定义一个方法不去实现,让继承的子类去实现,每个子类实现不一样
class Animal{
name:string;
constructor(name:string) {
this.name=name
}
run():void{
console.log(this.name+"在运动")
}
eat():void{ //父类定义的方法
console.log("我是不吃东西的种类")
}
}
class Dog extends Animal{
constructor(name:string) {
super(name)
}
eat():void{
console.log(this.name+"吃骨头")
}
}
class Cat extends Animal{
constructor(name:string) {
super(name)
}
eat():void{
console.log(this.name+"吃老鼠")
}
}
class Desk extends Animal{
constructor(name:string) {
super(name)
}
}
var d = new Dog('狗')
var c = new Cat('猫')
var des = new Desk('桌子')
d.eat() //狗吃骨头
c.eat() //猫吃老鼠
des.eat() //我是不吃东西的种类
抽象类以及抽象方法
- typescript的抽象类是提供其他类继承的基类 不能实例化调用
- 用abstract关键字定义抽象类以及抽象方法,抽象类中的抽象方法不包含具体实现但是其子类(也就是派生类)必须实现
- abstract的抽象方法只能在抽象类定义
abstract class Animal{ //父类定义了抽象类
name:string;
constructor(name:string) {
this.name=name
}
run():void{
console.log(this.name+"在运动")
}
abstract eat():any //抽象方法 父类抽象类定义了标准 子类必须含有这个eat方法
}
class Dog extends Animal{
constructor(name:string) {
super(name)
}
eat():void{ //子类定义了eat方法 运行没问题
console.log(this.name+"吃骨头")
}
}
class Cat extends Animal{ //注释掉eat方法以后 程序提示错误
constructor(name:string) {
super(name)
}
// eat():void{
// console.log(this.name+"吃老鼠")
// }
}
var a = new Animal('动物') // 错误 抽象类不能实例化