原型链继承:
/**1.原型链继承:
* 子类型的原型为父类型的实例对象
*/
function Supper() { //父类型
this.propName = 'sup';
}
Supper.prototype.display = function () { //父类型的原型中添加display方法
alert(this.propName);
}
function Subber() { //子类型
this.propName = 'sub';
}
Subber.prototype = new Supper(); //子类型的原型是父类型的实例对象
Subber.prototype.constructor = Subber; //修正子类型的原型的constructor属性
var sub = new Subber();
sub.display(); //sub 子类型继承了父类型的display方法
借用构造函数继承:
/**2.借用构造函数继承:
* 定义父类型构造函数
* 定义子类型构造函数
* 在子类型构造函数中调用父类型构造函数
*/
function Supper(name, age) {
this.name = name;
this.age = age;
}
function Subber(name, age, num) {
Supper.call(this, name, age);
this.num = num;
}
var sub = new Subber('doggy', 18, 68); //this -> sub
console.log(sub.name); //doggy
组合继承:
/**3.组合继承:
* 利用原型链实现对父类型的方法的继承
* 借用父类型构造函数实现初始化相同属性
*/
function Supper(name, age) {
this.name = name;
this.age = age;
}
Supper.prototype.setDate = function (date) {
this.date = date;
};
function Subber(name, age, num) {
Supper.call(this, name, age);
this.num = num;
}
Subber.prototype = new Supper(); //原型链继承
Subber.prototype.constructor = Subber; //修正constructor
var sub = new Subber('doggy', 18, 68);
console.log(sub.name); //doggy
sub.setDate(2019); //调用继承的方法
console.log(sub.date); //2019