构造函数继承方式:
Father.call(this, args);
构造函数继承的几个特点:
- 父类构造函数中的属性和方法都可以被子类继承;
- 父类原型上的属性和方法无法被继承;
- 父类实例上的属性和方法无法被继承;
- 父类构造函数中的属性和方法在所有子类实例中是不共享的;
- 创建子类实例时可以向父类构造函数传参;
- 允许多重继承(同时继承多个不同的父类)。
下面上一个构造函数继承的例子:
var Father = function (id) {
//父类构造函数中的属性和方法可以被继承
this.id = id;
this.type = "father";
this.getId = function () {
return this.id;
};
this.getType = function () {
return this.type;
};
};
var Mother = function (id) {
this.mType = "mother";
};
//父类原型上的属性和方法无法被继承
Father.prototype.gender = "male";
Father.prototype.getGender = function () {
return this.gender;
};
//父类实例上的属性和方法无法被继承
var father = new Father();
father.job = "driver";
father.getJob = function () {
return this.job;
};
var Son = function (id) {
//允许多重继承
Father.call(this, id);
Mother.call(this);
};
var son1 = new Son(1);
//打印结果为father father,表示:子类可以正常调用父类构造函数中的属性和方法
console.log(son1.type + " " + son1.getType());
//下面的打印会出错,提示son1.getGender不是方法,表示:子类无法调用父类原型上的属性和方法
// console.log(son1.getGender());
//打印结果为undefined driver driver,表示:子类无法获取父类实例上的属性(同样也无法调用父类实例上的方法)
console.log(son1.job + " " + father.job + " " + father.getJob());
//打印结果为father mother,表示:子类可以同时继承多个父类
console.log(son1.type + " " + son1.mType);
var son2 = new Son(2);
//打印结果为1 2,表示:父类构造函数中的属性和方法在所有子类实例中是不共享的
console.log(son1.id + " " + son2.id);