js继承

116 阅读1分钟

1.原型链继承

function Parent () {
  this.name = 'kevin';
}
Parent.prototype.getName = function () {
  console.log(this.name);
}
function Child () {
 
}
Child.prototype = new Parent();

var child1 = new Child();
 
console.log(child1.getName()) // kevin

问题:

1.引用类型的属性被所有实例共享 2.在创建 Child 的实例时,不能向Parent传参

2.借用构造函数(经典继承)

function Parent (name) {
  this.name = name;
}
 
function Child (name) {
  Parent.call(this, name);
}
 
var child1 = new Child('kevin');
 
console.log(child1.name); // kevin
 
var child2 = new Child('daisy');
 
console.log(child2.name); // daisy


缺点: 方法都在构造函数中定义,每次创建实例都会创建一遍方法。

3.组合继承

function Parent (name) {
  this.name = name;
  this.colors = ['red', 'blue', 'green'];
}
 
Parent.prototype.getName = function () {
  console.log(this.name)
}
 
function Child (name, age) {
 
  Parent.call(this, name);
   
  this.age = age;
 
}
 
Child.prototype = new Parent();
 
var child1 = new Child('kevin', '18');
 
child1.colors.push('black');
 
console.log(child1.name); // kevin
console.log(child1.age); // 18
console.log(child1.colors); // ["red", "blue", "green", "black"]
 
var child2 = new Child('daisy', '20');
 
console.log(child2.name); // daisy
console.log(child2.age); // 20
console.log(child2.colors); // ["red", "blue", "green"]


4.原型式继承

function createObj(o) {
  function F(){}
  F.prototype = o;
  return new F();
}

5. 寄生式继承

function createObj (o) {
  var clone = object.create(o);
  clone.sayName = function () {
    console.log('hi');
  }
  return clone;
}

6. 寄生组合式继承

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);