转自https://www.cnblogs.com/constantince/p/4754992.html
- 类式继承(构造函数)
类式继承是在函数对象内调用父类的构造函数,使得自身获得父类的方法和属性。call和apply方法为类式继承提供了支持。通过改变this的作用环境,使得子类本身具有父类的各种属性。
var father = function() {
this.age = 52;
this.say = function() {
alert('hello i am '+ this.name ' and i am '+this.age + 'years old');
}
}
var child = function() {
this.name = 'bill';
father.call(this);
}
var man = new child();
man.say();
- 原型继承
我们说的原型继承,就是将父对像的方法给子类的原型
var father = function() {
}
father.prototype.a = function() {
}
var child = function(){}
//开始继承
child.prototype = new father();
var man = new child();
man.a();
组合模式
用类式继承属性,而原型继承方法
属性继承:(需要用 call 修改 this 指向)调用父类的构造函数
方法继承:子类要继承的构造函数名.prototype=new 父类构造函数名();
function father() {
this.a = 'father'
}
father.prototype.b = function() {
alert(this.a)
}
var child = function() {
father.call(this)
}
child.prototype = new father();