一:构造函数绑定实现继承
含义:在子类内部调用父类的方法,通过call()/ apply()方法
function Person() {
this.foot = 2
}
function Student() {
Person.call(this)
}
console.log(new Student()); */
父类 gang(几港 3 4港)发动机 需要传参 bsx(变速箱类如 at变速箱 cvt变速箱 双离合变速箱)
function Car(gang,bsx) {
this.lunzi = 4;
this.gang = gang;
this.bsx =bsx;
}
function Student(name,price,gang,bsx) {
Car.apply(this,[gang,bsx]);
this.name=name;
this.price=price;
this.print=function(){
document.write(`${this.name}--${this.price}--${this.lunzi}个轮子--${this.gang}- -${this.bsx}`)
}
}
var stu1=new Student('奔驰','100万','4缸','9AT变速箱');
stu1.print();
二:组合继承:
含义: 也叫伪经典继承, 原型链和构造函数组合在一块, 原型链实现对原型属性和方法的继承, 借用构造函数实现对实例属性的继承
function Person() {
// 实例属性
this.foot = 2
this.head = 1
}
// 原型属性和方法
Person.prototype.weight = '70kg'
Person.prototype.eat = function () {
console.log('我会吃饭')
}
function Student() {
// 借用构造函数实现对实例属性的继承
Person.call(this)
}
// 原型链实现对原型属性和方法的继承
Student.prototype = new Person()
Student.prototype.contructor = Student
let stu1 = new Student()
/* console.log(stu1)
console.log(stu1.weight)
stu1.eat()
function Car() {
this.lunzi = 4
}
Car.prototype.run = function () {
document.write(`${this.name}--我有${this.lunzi}个轮子 会跑赛道`)
}
function Bc(name) {
Car.call(this)
this.name = name
}
Bc.prototype = new Car()
Bc.prototype.contructor = Bc
var stu2 = new Bc('奔驰')
stu2.run()
三:拷贝继承:
含义:把父对象的所有属性和方法,拷贝进子对象 ,将父对象的prototype对象中的属性拷贝给child对象的prototype对象
function Person(){};
Person.prototype.head=1;
Person.prototype.foot=2;
Person.prototype.eat=function(){
document.write('我会吃饭')
}
function Studen(){};
function extend(child,parent){
for(let key in parent.prototype){
child.prototype[key]=parent.prototype[key];
}
}
extend(Studen,Person)
let stu1=new Studen();
stu1.eat()
function Car() {}
Car.prototype.lunzi=4;
Car.prototype.run = function () {
document.write(`${this.name}--我有${this.lunzi}个轮子 会跑赛道`);
}
function Bc(name) {
this.name = name;
}
function extend(child,parent){
for(let key in parent.prototype){
child.prototype[key]=parent.prototype[key];
}
}
extend(Bc,Car)
var stu2 = new Bc('奔驰');
stu2.run();