构造继承
使用call和apply方法,将父对象的构造函数绑定在子对象上
function Parents (){
this.color = color ;
}
function Children(name){
this.name = name;
Parents.apply(this,arguments);
//这里的this用法是this的显示绑定
//第一个传入的参数是对象直接绑定传入的对象
//第二个是数组,它将作为参数传给Function(argument)
}
将父对象构造函数绑定在子对象上面
原型继承
每个对象都有原型,如果每个子类的原型都指向父类的示例 那子类就可以通过原型链 来使用父类的方法
Children.prototype = new Parents();
//此行之后Children.prototype.constructor 指向的 Parents
//本来是指向Children
Children.prototype.constructor = Children;
这样就可以使用啦
利用空对象继承
var temp = function(){};
temp.prototype = Parents.prototype;
Children.prototype = new temp();
Children.prototype.constructor = Children;
这样解决了直接将父子对象原型联系起来造成子对象更改引起的父对象属性也更改的副作用!
复制继承
直接把父类的不变属性都放在 prototype上 然后让子对象的原型去复制父元素的原型属性
function Parents(){
Parents.prototype.item = "human";
}
function Children(){
var p = Parents.prototype;
var c = Chlidren.prototype;
for(let i in p ){
c[i] = p[i];
}
}
prototype和apply、call比较简单 大多用构造函数和原型混合的方式
function Parents(){
this.name = "baba_mama";
}
function Children(){
this.age = 3;
}
Children.prototype = new Parents();
//省略了子类原型的构造器书写
ES6的extends
和java语言的extends很类似 需要定义父类 然后子类去继承
父类中的所有方法都是默认添加到子类的原型上 - -
原理也是原型
class P{
constructor(name,age){
this.name = name ;
this.age = age ;
}
getAge(){
return this.age;
}
}
class C extends P{
constructor(name,age){
super(name,age);
this.gender = "one";
}
}
super:既可以当做函数也可以当做对象。super可以作为父类的构造函数。子类只能在构造函数里面来调用super方法 作为对象的时候 super = Parent.prototype