- 原型链继承
function Parent() {
this.name = 'kevin';
}
function Child(){};
Parent.prototype.getName = function(){
console.log(this.name);
}
Child.prototype = new Parent();
let child1 = new Child();
console.log(child1.getName());//kevin
缺点:
1. 引用类型的数据被所有实例共享
2. 在创建实例时无法向继承的对象传参
- 构造函数继承
function Parent(name) {
this.name = name;
}
function Child(name) {
Parent.call(this, name);
}
let child1 = new Child('kevin');
let child2 = new Child('lisa');
console.log(child1.name);//kevin
console.log(child2.name);//lisa
缺点:
1.方法都在构造函数中定义,每次创建实例都要初始化方法
- 组合式继承
function Parent(name) {
this.name = name;
this.arr = ['red','blue'];
}
Parent.prototype.getName = function(){
console.log(this.name);
}
function Child(name, age) {
Parent.call(this, name);
this.age = age;
}
Child.prototype = new Parent;
Child.prototype.constructor = Child;
let child1 = new Child('kevin', 18);
child1.arr.push('pink');
console.log(child1.age);
console.log(child1.arr);
child1.getName();
let child2 = new Child('daisy', '20');
child2.arr.push('green');
console.log(child2.age);
console.log(child2.arr);
child2.getName();
- 原型式继承
就是Object.create()的仿写
function createObj(fn) {
function F(){}
F.prototype = fn;
return new F();
}
var person = {
name: 'kevin',
friends: ['daisy', 'kelly']
}
var person1 = createObj(person);
var person2 = createObj(person);
person1.name = 'person1';
console.log(person2.name); // kevin
person1.friends.push('taylor');
console.log(person2.friends); // ["daisy", "kelly", "taylor"]
缺点:
1.所有实例共享引用类型的值
- 寄生式继承
function createObj(o) {
var clone = Object.create(o);
clone.sayName = function (){
console.log('hi');
}
return clone
}
缺点:
跟构造函数一样,每次都会创建一次方法
- 寄生式组合继承
function object(o) {
function F() {}
F.prototype = o;
return new F();
}
function prototype(child, parent) {
var prototype = object(parent.prototype);
prototype.constructor = child;
child.prototype = prototype;
}
// 当我们使用的时候:
prototype(Child, Parent);