call和apply
call 和 apply 是用来改变this指向的
/* call 和 apply 都可以理解为是函数自身的方法
第一个参数代表了接下来this所代表的的对象 */
/* call和apply的区别 */
/* 使用call方法传参 一个一个传参*/
/* 使用appky方法传参 需要传一个数组,数组里面的第一个就对应了f函数里面第一个参数*/
console.log(f.call(obj1,'bmw','tangc'));
console.log(f.apply(obj2,['bmw','tangc']));
function Person(){
this.foot=2
}
function Student(){
Person.call(this)
}
console.log(new Student());
构造函数绑定的方式继承
/* 在子类的内部调用父类的方法
通过call()或者apply()打印到页面上 */
function Bmw(name,price,gang,bsx){
/* Car.call(this,gang,bsx); */
Car.apply(this,[gang,bsx])
this.name=name;
this.price=price;
this.intro=function(){
document.write(`${this.gang}${this.name}${this.bsx}${this.price}有${this.lunzi}个轮子`);
}
}
let qq=new Bmw('宝马','100w','4缸','8AT');
qq.intro();
组合继承
/* 也叫伪经典继承
将原型链继承和构造函数继承组合到一块
原型链实现对原型属性和方法的继承
借用构造函数实现对实例属性的继承 */
function Person(){
this.head=1;
this.foot=2;
}
Person.prototype.weight='70kg';
Person.prototype.eat=function(){
console.log('我会吃饭');
}
function Student(){
Person.call(this)
}
Student.prototype=new Person();
Student.prototype.constructor=Student;
let stu1=new Student();
拷贝继承
function Person(){};
Person.prototype.head=1;
Person.prototype.foot=2;
Person.prototype.eat=function(){
document.write('我会吃饭');
}
function Student(){}
function extend(child,parent){
for(let key in parent.prototype){
child.prototype[key]=parent.prototype[key];
}
};
extend(Student,Person);
let stu1=new Student();
console.log(stu1);
stu1.eat();