组合式继承
// 父类
function Person() {
// 父类的属性
this.hobbies = ['music', 'reading']
}
// 父类的函数
Person.prototype.say = function() {
console.log('person say')
}
// 子类
function Student() {
// 继承父类的属性(构造函数继承)
Person.bind(this)();
// Person.call(this);
// Person.apply(this); 一个意思
// 子类自己的属性
this.score = 90;
}
// 继承父类的函数(原型链继承)
Student.prototype = new Person();
// 所有涉及到原型链继承的继承方式都要修改子类构造函数的指向,否则子类实例的构造函数会指向父类。
Student.prototype.constructor = Student;
// console.log(Student.prototype.constructor)
// 子类自己的函数
Student.prototype.run = function() {
console.log('student run');
}
// new两个实例
var stu1 = new Student();
var stu2 = new Student();
// 实例的属性独立
stu1.hobbies.push('aaa');
console.log(stu1, stu2);
// 实例的函数共享
console.log(stu1.say === stu2.say);
console.log(stu1.run === stu2.run);
寄生组合式继承
// 实现继承的核心函数
function inheritPrototype(subType, superType) {
function F() {};
//F()的原型指向的是superType
F.prototype = superType.prototype;
//subType的原型指向的是F()
subType.prototype = new F();
// 重新将构造函数指向自己,修正构造函数
subType.prototype.constructor = subType;
}
// 父类
function Person() {
// 父类的属性
this.hobbies = ['music', 'reading']
}
// 父类的函数
Person.prototype.say = function() {
console.log('person say')
}
// 子类
function Student() {
// 继承父类的属性(构造函数继承)
Person.call(this);
// Person.apply(this); 一个意思
// 子类自己的属性
this.score = 90;
}
// 继承父类的prototype
inheritPrototype(Student, Person);
// 子类自己的函数
Student.prototype.run = function() {
console.log('student run');
}
// new两个实例
var stu1 = new Student();
var stu2 = new Student();
// 实例的属性独立
stu1.hobbies.push('aaa');
console.log(stu1, stu2);
// 实例的函数共享
console.log(stu1.say === stu2.say);
console.log(stu1.run === stu2.run);