1.call、apply继承:
<script>
let obj1 = {
a:'tom'
}
let obj2 = {
a:'jack'
}
function f(Car,House){
console.log(this);/* window */
return this.a
}
console.log(window.f);
/* call 和 apply是用来改变this指向的 */
console.log( f.call(obj1) );/* 指向obj1 */
/* call 和apply 都可以理解为是函数自身的方法
第一个参数代表了接下来this 所代表的对象
f.call(obj1) 会执行f这个方法 */
console.log( f.apply(obj1));
/* call和apply区别 */
/* 使用call来传参 */
console.log(f.call(obj1,'bmw','tangc'));
/* apply不能一个个的传参,需要传一个数组,数组里面第一个就对应f函数里面
的第一个参数,数组里面第二个就对应了f函数里面的第二个参数 */
console.log(f.apply(obj1,['bmw','tangc']));
function Person(){
this.foot = 2
}
function Student(){
Person.call(this)
}
console.log( new Student());
</script>
2.构造函数绑定方式实现继承:
<!-- 在子类内部调用父类的方法
通过call()或apply()方法 -->
<script>
function Car(gang,bsx){
this.lunzi = 4;
this.gang = gang;
this.bsx = bsx
}
function Student(name,price,gang,bsx){
Car.call(this,gang,bsx);
this.name = name;
this.price = price;
this.print = function (){
document.write(`${this.name}--${this.price}--${this.lunzi}个轮子
--${this.gang}--${this.bsx}`)
}
}
let bc1 = new Student('奔驰e300','55w','4缸','9At变速箱')
bc1.print()
/*
父类 Car lunzi 4 个
子类 name price 是通过传参
方法打印出 例如:奔驰 100w 有4个轮子 (从父类继承)
使用call 实现继承
*/
</script>
3.组合继承:
<!-- 组合继承,也叫伪经典继承,将原型链和构造函数组合在一块
原型链实现对原型继承和方法继承
借用构造函数实现实例属性的继承-->
<script>
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.constructor = Bc
let bc1 = new Bc('奔驰e300');
bc1.run()
/* 父类 Car lunzi 4 个 原型上有run方法打印 我有4个轮子我会跑
子类 Bc 自己有name 通过传参获得继承实例属性 lunzi 和原型方法run
方法打印出 例如:奔驰 100w 有4个轮子 会跑赛道
使用组合继承的方法 */
</script>
4.拷贝继承:
<!-- 把父对象所有属性和方法 , 拷贝进子对象 -->
<script>
/* 将父对象的 prototype 对象中的属性,
拷贝给Child对象的prototype对象 */
function extend(child,parent){
for(let key in parent.prototype){
child.prototype[key] = parent.prototype[key]
}
}
function Car (){}
Car.prototype.lunzi = 4;
Car.prototype.run = function (){
document.write(`我是${this.name}--我有${this.lunzi}个轮子,会跑赛道`)
}
/* console.log(Person.prototype); */
/* 子类 */
function Bc(name){
this.name = name;
}
extend(Bc,Car)
let bc1 = new Bc('宝马')
bc1.run()
/* 父类 Car 原型上 lunzi 4个 有run方法打印 ${this.name} 我有四个轮子 会跑赛道
子类 Bc 自己有name 通过传参获得拷贝继承 父亲原型上的lunzi 和方法run
要求 用子类 打印出 例如 : 奔驰 有4个轮子 会跑赛道
使用拷贝继承的方法 */
</script>