继承札记

类与实例

一. 类的声明与实例化

	function Person1() {
		this.name = 'name'
	}    //es5 
	
	class Person2 {
		constructor () {
			this.name = name
		}
	}     //es6
	
	new Person1()
	new Person2() //实例化的方式是一样的

类与继承

  1. 通过构造函数实现继承
	function Parent1() {
		this.name = 'parent1'
	} 
	function Child1() {
		Parent1.call(this)   //这里apply也可以
		this.type = 'child1'
	} 

	缺点:但是若在Parent1的原型链上新增方法,Child1是没发继承该方法的。由此看第二个方法。
  1. 借助原型链实现继承
   function Parent2() {
   	this.name = 'parent2'
   } 
   function Child2() {
   	this.type = 'child2'
   } 
   Child2.prototype = new Parent2() 
   /**
   *对最后这行代码进行解读:
   *Child2是没有name属性的,如果访问,child2内部找不到,
   *则向其原型链上寻找也就是 new Child2().__proto__ 上寻找,
   *显然new Child2().__proto__ 就是Child2.prototype ,
   *而Child2.prototype赋值为new Parent2(),
   *Child2的name属性就是new Parent2() 的name属性,实现了继承
   */
   /**
   *缺点:若实例化两个Child2,其中一个改变name属性则另一个实例属性的name也会改变,因为两个实例的原型链都是一样的,这显然不是我们需要的,下边看第三种方式
   *

若对原型链不熟悉的同学请看另一篇文章原型链小结
3. 组合方式

   function Parent3() {
   	this.name = 'parent3'
   } 
   function Child3() {
   	Parent3.call(this)
   	this.type = 'child3'
   } 
   Child3.prototype = Parent3.prototype

缺点:Child3.constructor为Parent3,我们希望是Child3
  1. 组合继承优化2
   function Parent4() {
   	this.name = 'parent4'
   } 
   function Child4() {
   	Parent4.call(this)
   	this.type = 'child4'
   } 
   Child4.prototype =Object.create(Parent4.prototype)
   Child4.prototype.constructor = Child4

猜你喜欢

转载自blog.csdn.net/weixin_41643133/article/details/88747838