面向对象-继承

来源:互联网 发布:广州大学生数据分析 编辑:程序博客网 时间:2024/06/13 18:48

//创建一个person类
function Person (name,sex) {
//添加属性
this.name = name;
this.sex = sex;
//添加方法
this.intro = function  () {
alert('姓名' + this.name +'性别' + this.sex);
}

}
//使用原型
Person.prototype = {
//原型中的方法
study:function  () {
alert('Person在学习');

}
}


//继承:子类继承父类所有的特征(属性)和行为(方法)
//创建一个学生student类,继承自person类


function Student (name,sex) {
//使用call继承
//student继承person类 this代表student对象
//对象1.call(对象,参数1,参数2,参数3);
//含义:对象2继承自对象1,也就是集成到对象1里的所有的属性和方法;
Person.call(this,name,sex);
    //第二种方式
   //对象1.apply(对象2,[参数1,参数2....])
   //Person.apply(this,[name,sex]);
   
    //单独设置子级独有的属性
    this.age = 18;
   
   
}


//原型继承 子类继承父类的原型
//注意:原型继承一定要写在创建对象之前
Student.prototype = new Person();

//添加原型中的方法
Student.prototype.play = function  () {

alert('玩耍');
   
}
//重写原型中的方法(父级的方法实现的功能不能满足子级的需要,则需要重写父级的方法实现)


//父级的对象调用父级的方法,子级调用自己的方法
Student.prototype.study = function  () {
alert('student在学习,这是重写后的方法');
}
//创建对象
var per1 = new Person('老爸','man');
var stu1 = new Student('大头','boy');

//父级中访问属性和调用方法
//alert(per1.name);
//per1.intro();
//子集对象继承了父级里的属性
//alert(stu1.name);
//子集对象继承了父级里的方法
//stu1.intro();
//per1.study(); 
//父级对象调用原型里的方法

//stu1.study();//子级调用父级中原型里的方法,报错

//原因:对于继承,我们必须做到原型对象也继承;


//原型的继承必须写在创建对象之前!!!例如: 之前的原型继承操作


//alert(stu1.age);//子级访问自己独有的属性


//alert(per1.age); //父级不能访问子级独有的属性


//per1.study();


stu1.study(); //调用的是子级重写后的方法


0 0
原创粉丝点击