欢迎加入qq群(IT-程序猿-技术交流群):757345416
今天我们来研究下JavaScript中的继承:
es5:
//构造器函数
function Person(name,age,sex){
this.name=name;
this.age=age;
this.sex=sex;
}
Person.prototype.study=function(){
console.log("好好学习,天天向上")
};
function Student(name,age,sex,sno,sdept){
Person.call(this,name,age,sex);
//也可以使用apply实现继承
//Person.apply(this,[name,age,sex]);
this.sno=sno;
this.sdept=sdept;
}
Student.prototype.showInfo=function(){
alert(this.sno+this.sdept+this.name+this.sex+this.age);
};
//继承父类的方法
for(var i in Person.prototype){
Student.prototype[i]=Person.prototype[i];
}
var s1=new Student("1001","计算机","tom",19,"男");
es6:
class Person{
constructor(name,age,sex){
this.name=name;
this.age=age;
this.sex=sex;
}
say(){
console.log("态度决定一切");
}
}
//子类
class Student extends Person{
constructor(name,age,sex,num,school){
super(name,age,sex);
this.num=num;
this.school=school;
}
say(){
console.log("这是子类中的say()");
}
study(){
console.log("持之以恒");
}
}
let s1 = new Student("tom",19,"男",1001,"高级大学");
文章到此结束,希望对你的学习有帮助!