在 JavaScript 中,ES6 开始引入class的概念。实际上,JavaScript 中class的本质也是基于原型prototype的实现方式作了进一步的封装,其本质还是函数function。虽说如此,class和function还是有不同之处。
function:
<script>
function Person(name,age) {
this.name=name;
this.age=age;
}
Person.prototype.say=function() {
console.log(this.name,"Hello")
}
function Student(name,age,grade){
Person.call(this,name,age)
this.grade=grade;
}
var obj=new Student("hrefan","100","100")
console.log(obj)
</script>
class:
<script>
//父类
class Person{
constructor(name,age){
this.name = name;
this.age = age;
}
say(){
console.log(this.name,"hello")
}
}
//子类
//extends 原型继承
class Student extends Person {
constructor(name,age,grade){
//构造函数写法:Person.call(this,name,age)
super(name,age);
this.grade = grade;
}
}
var obj=new Student("Jack","32","100");
console.log(obj);
//构造函数中子类想要使用父类方法还需要:Student.prototype=new Person();,而class这边可以直接用,不仅仅属性,方法也一起继承了
obj.say();
覆盖父类方法:
//覆盖父类方法,只需要起相同名字,让方法调用时先找到子类的,父类就被忽略了
say() {
console.log(this.name, "你好");
}
让父类方法也显示:
say() {
//让父类方法也显示:
super.say()
console.log(this.name, "你好");
}