javascript 原型和继承

1,443 阅读5分钟

如题,准备面试一次就看一次,索性自己好好总结一下吧,一劳永逸。

本文从以下几个方面着手

  • 0怎么理解面向对象
  • 1创建对象的方式
  • 2记住原型链的小窍门
  • 3instanceof 模拟实现
  • 4new关键字 模拟实现
  • 5继承的实现(逐步实现)

0 怎么理解面向对象

其实我也不知道咋回答这问题,我只知道,面试官问这个后,就表示他要问一堆继承的问题了。下面是引用周老师的一段说辞。

"面向对象是一种编程思想 与面向过程是对应的 一般的语言都是面向对象的 js本身也是基于面向对象构建出来的 ,例如 js本身就有很多内置类,Promise就是,可以new Promise来创建一个实例,来管理异步编程 。 还有vue 也是,平时都是创建vue的实例啊。"

1 创建对象的方式

1.对象字面量

var o1 = {name: 'o1'}
var o2 = new Object({name: 'o2'})

2.通过构造函数

var M = function(name){
	this.name = name
}
var o3 = new M('o3')

3.Object.create

var o4 = Object.create(p)

2 记住原型链的小窍门

记忆总是有规律的,如高中时期学的三角函数,需要背公式很多,强行去背全部的公式是容易混乱的。不过如果把核心的几点背牢,其余的公式只需要稍加推导即可。关于原型链也是一样,有几点在最开始就记住的话,后面就不会乱了。原型链中关键概念:构造函数实例constructor__ proto__prototype, 首先要记住他们的关系

  • 实例(对象)有__proto__ , 实例(对象)没有prototype
  • 构造函数有 prototype ,同时prototype又是对象,那么prototype即满足上面一条,除了拥有__proto__外,还含有constructor
  • 构造函数的prototype的constructor就是指向构造函数本身,即上例子中 M.prototype.constructor === M

上面3点请先牢记,后面所总结的完整继承和这有紧密的关联

其实 构造函数实例constructor__ proto__prototype 的关系已经在上面的例子和3点介绍中介绍完了。不妨再回顾一下

  1. 构造函数即普通函数,只不过前边有 new 关键字

  2. 通过 new构造函数 ,生成的对象即为实例。

  3. 以上面生成o3实例为例子

     o3.__proto__ === M.prototype  //true
    
     o3.prototype   //undefined
    
     o3.__proto__ === M.prototype //true
    
  4. o3实例本身并无constructor,不过会借助原型链向上查找,即,

     o3.constructor === M.prototype.constructor  // true
    
     o3.constructor === M //true
    

小结 理清这几个关键词的关系后,原型链就明朗很多了

3 instanceof 模拟实现

instanceof 的原理是什么呢? 先来看一下使用

[] instanceof Array  // true

即左边是对象,右边是类型,instanceof 就是要判断右边类型的prototype,是否在左边实例的原型链上,如下例子所示

[].__proto__ === Array.prototype //true
Array.prototype.__proto__ === Object.prototype //true
Object.prototype__proto__ //null

那么依据这个思想来实现一下instanceof吧,一定会印象更加深刻

function myInstanceof2(left, right){
	if(left === null || left === undefined){
		return false
	}
	if(right.prototype === left.__proto__) {
		return true
	}

	left = left.__proto__
	return myInstanceof2(left, right)
}

console.log(myInstanceof2([], Array))

4 new 模拟实现(简要版)

new的过程发生了什么?

  1. 生成空对象

  2. 这个空对象的__proto__赋值为构造函数的prototype

  3. 绑定this指向

  4. 返回这个对象

     // 构造函数
     function M(name){
     	this.name = name
     }
     // 原生new
     var obj = new M('123')
    
     // 模拟实现
     function create() {
       // 生成空对象
       let obj = {}
       // 拿到传进来参数的第一项,并改变参数类数组
       let Con = [].shift.call(arguments)
       // 对空对象的原型指向赋值
       obj.__proto__ = Con.prototype
       // 绑定this 
       //(对应下面使用来说明:Con是参数第一项M,
       // arguments是参数['123'],
       // 就是 M方法执行,参数是'123',执行这个函数的this是obj)
       let result = Con.apply(obj, arguments)
       return result instanceof Object ? result : obj
     }
    
     var testObj = create(M, '123')
     console.log('testObj', testObj)
    

5 继承的实现(逐步实现)

一步一步来,从简到繁,更能直观发现继承的原理与缺点

  1. 构造方法方式 核心 Parent1.call(this)

     // 构造方法方式
     function Parent1(){
     	this.name = 'Parent1'
     }
     Parent1.prototype.say = function () {
     	alert('say')
     }
     function Child1(){
     	Parent1.call(this)
     	this.type = 'type'
     }
    
     var c1 = new Child1()
     c1.say() //报错
    

缺点: 只能继承父类构造函数内部属性,无法继承父类构造函数原型对象上属性

思考: 为什么 call 实现了继承,call本质是什么?

  1. 只借助原型继承 核心 Child2.prototype = new Parent2()

     // 原型
     function Parent2(){
     	this.name = 'Parent2'
     	this.arr = [1,2]
     }
     Parent2.prototype.say = function () {
     	alert('say')
     }
     function Child2(){
     	// Parent2.call(this)
     	this.type = 'type'
     }
     Child2.prototype = new Parent2()
    
     var c21 = new Child2()
     var c22 = new Child2()
    
     c21.say()
     c21.arr.push('9')
     console.log('c21.arr : ', c21.arr)
     console.log('c22.arr : ', c22.arr)
    

缺点: c21.arr 与c22.arr对应的是同一个引用

思考:为什么这么写是同一个引用?

  1. 组合继承1

把上面两个继承方式的优点合并起来,缺点都抛弃掉

 function Parent3(){
	this.name = 'Parent3'
	this.arr = [1,2]
}
Parent3.prototype.say = function () {
	alert('say')
}
function Child3(){
	Parent3.call(this)
	this.type = 'type'
}
Child3.prototype = new Parent3()

var c31 = new Child3()
var c32 = new Child3()

c31.say()
c31.arr.push('9')
console.log('c31.arr : ', c31.arr)
console.log('c31.arr : ', c32.arr)

思考: 这么写就没有问题了吗?

答 : 生成一个实例要执行 Parent3.call(this) , new Child3(),也就是Parent3执行了两遍。

  1. 组合继承2

改变上例子 的

  Child3.prototype = new Parent3()

  Child3.prototype = Parent3.prototype

缺点 : 很明显,无法定义子类构造函数原型私有的方法

  1. 组合继承优化3 再次改变上例子 的

    Child3.prototype = Parent3.prototype
    

   Child3.prototype = Object.create(Parent3.prototype)

问题就都解决了。 因为Object.create的原理是:生成一个对象,这个对象的__proto__, 指向所传的参数。

思考 :是否还有疏漏?一时想不起来的话,可以看下这几个结果

console.log(c31 instanceof Child3) // true
console.log(c31 instanceof Parent3) // true
console.log(c31.constructor === Child3) // false
console.log(c31.constructor === Parent3) // true

所以回想起文章开头所说的那几个需要牢记的点,就需要重新赋值一下子类构造函数的constructor: Child3.prototype.constructor = Child3,完整版如下

function Parent3(){
	this.name = 'Parent3'
	this.arr = [1,2]
}
Parent3.prototype.say = function () {
	alert('say')
}
function Child3(){
	Parent3.call(this)
	this.type = 'type'
}

Child3.prototype = Object.create(Parent3.prototype)
Child3.prototype.constructor = Child3

var c31 = new Child3()
var c32 = new Child3()

c31.say()
c31.arr.push('9')
console.log('c31.arr : ', c31.arr)
console.log('c31.arr : ', c32.arr)

console.log('c31 instanceof Child3 : ', c31 instanceof Child3)
console.log('c31 instanceof Parent3 : ', c31 instanceof Parent3)
console.log('c31.constructor === Child3 : ', c31.constructor === Child3)
console.log('c31.constructor === Parent3 : ', c31.constructor === Parent3)

5 es6的继承

class Parent{
  constructor(name) {
    this.name = name
  }
  getName(){
    return this.name
  }
}
    
class Child{
  constructor(age) {
    this.age = age
  }
  getAge(){
    return this.age
  }
}

es6继承记住几个注意事项吧

  • 1 构造函数不能当普通函数一样执行 Parent() 是会报错的
  • 2 不允许重定向原型 Child.prototype = Object.create(Parent.prototype) 无用
  • 3 继承写法如下,上面的Child类想继承父类,改成如下写法就好

注意写了extends关键字,constructor中就必须写super(),打印结果如下: