构造函数和继承方法

构造函数

类的声明

1.function声明

function Animal(name){
this.name = name
}

2.class声明

class Animal{
   constructor(name){
    this.name = name
  }
}

类的实例化

通过 new 操作符实例化

let animal = new Animal('pig')

类的继承

// 借助构造函数实现继承

function Parent1 () {
 this.name = 'parent1'
}
function Child1 () {
 Parent1.call(this);
 this.type = 'child1'
}

// 不足 ,不能完全继承Parent1原型上的属性和方法 
// 例如 定义 Parent1.prototype.pName = 'pName' Child1就无法继承
// 借助原型链实现继承
function Parent2 () {
  this.name  =  'parent2'
  this.arr = [1,2,3]
};
function Child2(){
  this.type = 'child2'
}
Child2.prototype = new Parent2();
// 不足, 如果在构造函数中存在一个对象,那么修改一个实例会影响另一个实例的对象参数,
// 因为 s1.__proto__ === s2.__proto__ 公用一个原型对象,里面的arr又是引用类型的值
s1 = new Child2();
s2 = new Child2();

s1.arr.push(4)

console.log(s1.arr,s2.arr)  // (4) [1, 2, 3, 4] (4) [1, 2, 3, 4]
// 组合方式1
function Parent31(){
  this.name = 'p31';
  this.arr = [1,2,3]
}
function Child31 () {
  Parent31.call(this); // 获取构造体中的属性和方法
  this.type = 'c31';
}
Child31.prototype = new Parent31(); // 获取原型上的属性和方法

var s3 = new Child31();
var s4 = new Child31();

s3.arr.push(4)

console.log(s3.arr,s4.arr) // [1,2,3,4]  [1,2,3]

// 组合优化2,减少Parent31构造函数运行次数
function Parent33(){
  this.name = 'p33'
}
function Child33 () {
  Parent33.call(this); // 获取构造体中的属性和方法
  this.type = 'c33';
}
var test= new Child33();
Child33.prototype = Parent33.prototype; // 获取原型上的属性和方法
// 因为以上两种继承方式的 prototype 是一个导致 他们的constructor是一样的
console.log(test instanceof Child33, test instanceof Parent33) // true true


// 组合优化3

function Parent5(){
  this.name = 'p5'
}
function Child5 () {
  Parent5.call(this); // 获取构造体中的属性和方法
  this.type = 'c5';
}
var test2= new Child5();
Child5.prototype = Object.create(Parent5.prototype); 
Child5.prototype.constructor = child5
//object.create 方法创建一个新对象,使用现有的对象来提供新创建的对象的__proto__ 获取原型上的属性和方法 ,更改constructor console.log(test2 instanceof Child5, test2 instanceof Parent5) // true false
// es6 class 继承方式 extends
class A{
  constructor(){
    this.name = 'a'
  }
  say(){
   console.log('say')
  }
}
// 使用 extends B继承A的,实例后有instanceof问题 class B extends A { constructor(){ super();
// 相当于 A.prototype.constructor.call(this) this.type = 'b' } }
原文地址:https://www.cnblogs.com/lizhiwei8/p/11642080.html