js中通過原型來實現(xiàn)繼承
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;
}
//改變學(xué)生的原型的指向即可==========>學(xué)生和人已經(jīng)發(fā)生關(guān)系
Student.prototype=new Person("小明",10,"男");
Student.prototype.study=function () {
console.log("學(xué)習(xí)很累很累的哦.");
};
//相同的代碼太多,造成了代碼的冗余(重復(fù)的代碼)
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("下面的是學(xué)生對象中自己有的");
console.log(stu.score);
stu.study();
組合繼承:原型繼承+借用構(gòu)造函數(shù)繼承
// TODO:構(gòu)造函數(shù)
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:借用構(gòu)造函數(shù):屬性值重復(fù)的問題
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();
//屬性和方法都被繼承了