a. 构造函数继承:属性的继承
Function.prototype.call(thisArg, arg1, arg2, ...)
-- 作用:实现函数调用,在函数调用执行时,函数体中的 this 指向 call() 方法第一个参数 thisArg 所表示的对象。
-- arg1, arg2, ... 表示调用在被调用时传递的参数列表。
-- 注意,如果 thisArg 是 null,则在函数调用时,函数体中的 this 指向全局对象(浏览器中是 window)。
Function.prototype.apply(thisArg, arguments|[])
借用构造函数的基本思想就是利用call或者apply把父类中通过this指定的属性和方法复制(借用)到子类创建的实例中。因为this对象是在运行时基于函数的执行环境绑定的
。
如何求一个数组中元素的最大值
Math.max.apply(null, array)
Math.min.apply(null, array)
b. 原型继承:方法的继承
例:
Student.prototype = new Person();
或
Student.prototype = Object.create(Person.prototype);
c. 组合继承
d. class
实质上是 JavaScript 现有的基于原型的继承的语法糖
继承: extends ---- 子类 extends 父类
子类调用父类:
super:
super() -- 子类构造函数中调用父类的构造函数,必须是第一条语句
super.methodName() -- 子类调用父类方法
e. 拷贝式继承
f. 实例继承
g. 寄生组合继承
<script type="text/javascript">
// 原型继承
function Public(){}
Public.prototype = {
xiao : function(){
console.log("hahahhahaha")
}
}
function Me(){};
Me.prototype = new Public();
Me.prototype.eat = function(){
console.log("haha");
}
function Ta(){};
Ta.prototype = Object.create(Public.prototype);
Ta.prototype.he = function(){
console.log("heshui");
}
var obj = new Me();
var obj2 = new Ta()
obj.xiao()//console.log("hahahhahaha")
obj2.xiao()//console.log("hahahhahaha")
// 用class实现继承
class Pepole {
constructor(name, age, sex){
this.name = name;
this.age = age;
this.sex = sex;
}
eat(){
console.log("chi");
}
sleep(){
console.log("shuijiao");
}
}
class Son extends Pepole{
constructor (name, age, sex, play){
super(name, age, sex);//超类,直接调用父类构造函数(必须是构造构造函数的第一条语句)
this.play = play;
}
doHomeWork(){
console.log("做作业");
}
}
var lin2 = new Son("LIN", "20", "MM", "lol");
console.log(lin2.play)//LIN
lin2.eat()//console.log("chi");
lin2.doHomeWork()//console.log("做作业");
// 拷贝式继承
Function.prototype.extend = function(parent, options){
for(var attr in parent.prototype){
this.prototype[attr] = parent.prototype[attr];
}
for(var attr in options){
this.prototype[attr] = options[attr];
}
}
function Pepole2(name, age, sex){
this.name = name;
this.age = age;
this.sex = sex;
}
Pepole2.prototype = {
likes : function(){
console.log("吃零食");
},
works : function(){
console.log("睡瞌睡");
}
}
function NewSon(name, age, sex, play){
Pepole2.call(this, name, age, sex);//借用构造函数继承属性
this.play = play;
};
NewSon.extend(Pepole2);//拷贝父类原型方法到Function的自定义属性extend中,使所有函数都能用extend来调用拷贝的原型方法
var lin3 = new NewSon("linlin", "99", "nan", "nba 2k");
console.log(lin3.age)
function Abc(){}
Abc.extend(Pepole2, {
runs : function(){
console.log("baseball");
}
});
var def = new Abc();
def.runs()//console.log("baseball");
</script>