js中class继承和super

js中class继承和super

1.class的简单介绍

先看一段构造函数的代码
function Person(name,age) {
    this.name = name;
    this.age=age;
}
Person.prototype.say = function(){
    return "我的名字叫" + this.name+"今年"+this.age+"岁了";
}
var obj=new Person("laotie",88);//通过构造函数创建对象,必须使用new 运算符
console.log(obj.say());//我的名字叫laotie今年88岁了
同样我们用class实现下
class Person{//定义了一个名字为Person的类
    constructor(name,age){//constructor是一个构造方法,用来接收参数
	//每个class都有一个constructor!
        this.name = name;//this代表的是实例对象
        this.age=age;
    }
    say(){//这是一个类的方法,注意千万不要加上function
        return "我的名字叫" + this.name+"今年"+this.age+"岁了";
    }
}
var obj=new Person("laotie",88);
console.log(obj.say());//我的名字叫laotie今年88岁了
两段代码功能基本一致,那么为什么要用class呢? 

es5中只有对象,没有类的概念。它对java等程序员不太友好,所以class就出现了。

1.constructor是一个构造器 每个类对应一个构造器。
2.上图的say()写法注意:不要加上function
那么关于class的简单介绍就到这里了。

2.class的继承

同样的,我们先看看不用class实现的继承
function animal(){
	this.a=1;
}
animal.prototype.dw=function(){
	console.log("动物的原型方法")
}
function Dog(){
	this.b=2;
}
Dog.prototype.sy=function(){
	console.log("sy")
}
Dog.prototype=new animal()//1.这句话把Dog的原型指向了animal
var hashiqi=new Dog();
hashiqi.dw();//2.Dog的实例对象hashiqi便有了动物的原型方法dw
hashiqi.sy();//3.Dog的实例对象hashiqi便失去了构造函数原有的原型方法sy
console.log(hashiqi.a);//4.Dog的实例对象hashiqi便有了动物的所有属性,如上面的a
console.log(hashiqi.b);//5.Dog的实例对象hashiqi构造函数的属性未失去,如上面的bark
console.dir(hashiqi)

很简单通过修改原型指向实现了继承当然还有其他方法比如call和apply

	接下来我们看看class实习的继承语法
class Animal{
	constructor(name) {
	    this.name=name
	}
	eat(){
		console.log(`${this.name}`);
	}
}
class Dog extends Animal{
	constructor(name,age){
		super(name)
		//但凡看到extends继承那这句就固定加上super
		//相当于es5中Animal.call(this,name)
		//super()负责初始化this.相当于ES5中的call和apply方法。
		this.name=name
		this.age=age
	}
	say(){
		console.log(`${this.name}=>${this.age}`)
	}
}
var dog=new Dog("cxk",12);
dog.say()
dog.eat()

ES5中,我们通过在继承的函数中调用call()或者apply()方法实现继承。
但凡看到extends继承那这句就固定加上super
在es5中我们用 被继承的函数名.call(this,参数,…参数) 来修改this的指向
那么这里的super()负责初始化this.就相当于ES5中的call和apply方法。

  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值