一、原型链继承
function Show() {
this.name = ['1','2']
}
function Run() {}
Run.prototype = new Show();
var run = new Run()
run instanceof Show // true
run instanceof Run // false
run.proto.constructor === Show // true
var run1 = new Run()
var run2 = new Run()
run1.name.push('3') // ['1','2','3']
run2.name // ['1','2','3'] 共享引用属性
无法向父类构造函数传参
构造器的指向对象更改了,不符合目的,无法判别出new出来的实例属于谁
父类的所有属性被共享,一个实例修改了属性,其他子类实例都会受影响
二、构造函数继承
function Show(name) {
this.name = name
}
function Run(name) {
Show.apply(this,arguments)
}
var run1 = new Run()
var run2 = new Run()
run1.name = 2
只能继承父类的实例属性和方法,不能继承原型属性和方法
方法都定义在构造函数中,每次创建实例都会创建一遍方法,无法实现函数复用,影响性能。
三、组合继承
function Show(name) {
this.name = name
}
function Run(name) {
Show.apply(this,arguments) //第二次调用
}
Run.prototype = new Show() // 第一次调用
Run.prototype.constructor = Run
会调用两次父类构造函数。
四、寄生式组合继承
function Show (name) {
this.name = name;
this.colors = ['blue', 'red'];
}
Show.prototype.getName = function () {
console.log(this.name);
}
function Run (name, age) {
// 通过借用构造函数继承父类的实例属性和方法
Show.call(this, name);
this.school = age; // 添加新的子类属性
}
// 声明继承函数
function extend(Child, Parent) {
var F = function () {};
F.prototype = Parent.prototype;
Child.prototype = new F();
Child.prototype.constructor = Child;
}
// 寄生式继承父类原型属性和方法
extend(Run, Show);
var p1 = new Run('Leo', 26);
var p2 = new Run('Tom', 20);
p1.colors.push('green');
p1.getName(); // Leo
console.log(p1.colors); //["blue", "red", "green"]
console.log(p2.colors); //["blue", "red"]