拷贝对象、组合继承、构造函数绑定实现继承、call 和 apply 的区别

111 阅读1分钟

【拷贝对象】

 

【事例】

父类 Car 原型上 lunzi 4个 有run方法打印

${this.name} 我有4个轮子 会跑赛道

子类 Bc 有自己的属性name 通过传参获得

拷贝继承 父类原型上的 lunzi 和 方法run

要求 用子类 打印出 例如 : 奔驰 有 4 个轮子 会跑赛道

使用拷贝继承的方法

function Car() { }

Car.prototype.lunzi = 4;

Car.prototype.run = function () {

document.write(`this.name{this.name}--{this.lunzi}个轮子--会跑赛道`);

}

function Bc(name){

this.name = name;

}

extend(Bc,Car)

new产生了实例bc1 把构造函数Bc的属性和方法都给了实例

构造函数Bc的this是指向实例bc1 

let bc1 = new Bc('宝马');

bc1.run();

【组合继承】

也叫伪经典继承

将原型链继承和构造函数继承组合在一块

原型链实现对原型属性和方法的继承

借用构造函数实现对实例属性的继承

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.contructor = Student;

 let stu1 = new Student();

 console.log(stu1);

 console.log(stu1.weight);

【构造函数绑定实现继承】

在子类的内部调用父类的方法

通过call()或apply()方法

function Person(){

 this.foot = 2

 }

 function Student(color,price){

 Person.call(this)

 }

 console.log( new Student('白色','100w') );

【call 和 apply 的区别】

call 和 apply 是用来改变this指向的 

call和apply都可以理解为是函数自身的方法

第一个参数代表了 接下来this所代表的对象 

 f.call(obj1) 会执行f这个方法 

 console.log( f.call(obj1) )    this=>obj1 

 console.log( f.call(obj2) )    this=>obj2 

 console.log( f.apply(obj1) )    this=>obj1 

 console.log( f.apply(obj2) )    this=>obj2 

 call和apply的区别 

 使用call方法来传参 一个一个的传参 

 console.log( f.call(obj1,'bmw','tangc') ) /* this=>obj1 

 使用apply方法来传参 需要传一个数组 数组里面的第一个就对应了f函数里面的

第一个参数,数组里面的第二个就对应了f函数里面的

第二个参数 

 console.log( f.apply(obj1,['bmw','tangc']) )

function Person(){

this.foot = 2

}

function Student(){

Person.call(this)

}

console.log( new Student() );