js中通过原型来实现继承
function Person(name,age,sex) {
this.name=name;
this.sex=sex;
this.age=age;
}
Person.prototype.eat=function () {
console.log("人可以吃东西");
};
Person.prototype.sleep=function () {
console.log("人在睡觉");
};
Person.prototype.play=function () {
console.log("生活就是不一样的玩法而已");
};
function Student(score) {
this.score=score;
}
//改变学生的原型的指向即可==========>学生和人已经发生关系
Student.prototype=new Person("小明",10,"男");
Student.prototype.study=function () {
console.log("学习很累很累的哦.");
};
//相同的代码太多,造成了代码的冗余(重复的代码)
var stu=new Student(100);
console.log(stu.name);
console.log(stu.age);
console.log(stu.sex);
stu.eat();
stu.play();
stu.sleep();
console.log("下面的是学生对象中自己有的");
console.log(stu.score);
stu.study();
组合继承:原型继承+借用构造函数继承
// TODO:构造函数
function Person(name,age,sex) {
this.name=name;
this.age=age;
this.sex=sex;
}
// TODO:原型添加方法:
Person.prototype.sayHi=function () {
console.log("阿涅哈斯诶呦");
};
function Student(name,age,sex,score) {
// TODO:借用构造函数:属性值重复的问题
Person.call(this,name,age,sex);
this.score=score;
}
//改变原型指向----继承
Student.prototype=new Person();//不传值
Student.prototype.eat=function () {
console.log("吃东西");
};
var stu=new Student("小黑",20,"男","100分");
console.log(stu.name,stu.age,stu.sex,stu.score);
stu.sayHi();
stu.eat();
var stu2=new Student("小黑黑",200,"男人","1010分");
console.log(stu2.name,stu2.age,stu2.sex,stu2.score);
stu2.sayHi();
stu2.eat();
//属性和方法都被继承了
网友评论