js中虽然没有类的概念,但可以通过构造函数加原型链的方式实现类的继承。下面是一道简单的题目
请使用Js代码写出一个类继承的模型,需包含以下实现:
定义父类和子类,并创建父类和子类的属性和方法
子类继承父类的属性和方法
在创建子类对象时,调用父类构造函数
//父类构造函数
function Person(name,cardid){
//父类属性
this.name=name;
this.cardid=cardid;
}
//父类方法
Person.prototype.getName=function(){
return this.name;
}
//子类构造函数
function Student(name,age){
//子类属性
this.name=name;
this.age=age;
}
//子类的原型属性指向父类的实例,实现子类继承父类
Student.prototype=new Person();
//子类方法
Student.prototype.getAge=function(){
return this.age;
}
//子类的原型对象的构造函数指向子类本身
Student.prototype.constructor=Student;
var student1=new Student('zhou','25');
console.log(student1.getAge());
console.log(student1.getName());