js继承的三种实现

概念:在有些面向对象语言中,可以使用一个类(子类)继承另一个类(父类),子类可以拥有父类的属性和方法,这个功能可以在js中进行模拟。

三种方法:

第一种:扩展Object方法

 Object.prototype.ext=function(parObject){//Object.prototype.ext在原型链上定义的ext所有的对象都可以访问到
//循环遍历父类对象所有属性
for(var i in parObject){
//为子类对象添加这个遍历到的属性
//它的值是父类对象这个属性的属性值
this[i] = parObject[i];
}
}
function Person(p_name,p_age){
this.name=p_name;
this.age=p_age;
this.speak=function(){
alert(this.name+this.age);
}
}
function Student(p_no){
this.no=p_no;
this.say=function(){
alert(this.no+this.name_this.age);
}
}
var stu = new Student(101);
stu.ext(new Person('xiaoqiang',20));
stu.speak();
stu.say();

第二种:使用call和apply方法

 function Person(p_name,p_age){
this.name=p_name;
this.age=p_age;
this.speak=function(){
alert(this.name+this.age);
}
}
function Student(p_no,p_name,p_age){
this.no=p_no;
this.say=function(){
alert(this.name+this.age+this.no);
}
Person.call(this,p_name,p_age);//this是上下文,后面的参数是传递给person的参数,参数的先后顺序要一一对应,如果是用apply则后面的参数要用数组
}
var stu = new Student(8,'zhagsan',18);
stu.speak();
stu.say();

第三种:原型继承

 function Person(p_name,p_age){
this.name=p_name;
this.age=p_age;
this.speak=function(){
alert(this.name+this.age);
}
}
function Student(p_no){
this.no=p_no;
this.say=function(){
alert(this.name+this.age+this.no);
}
}
Student.prototype = new Person('wangwu',21);
var stu = new Student(10);
stu.speak();
stu.say();
上一篇:【MyBatis源码分析】insert方法、update方法、delete方法处理流程(下篇)


下一篇:在C#中如何定义一个变长的结构数组?如果定义好了,如何获得当前数组的长度?