js中的原型和原型链的理解

原型和原型链的理解

先来总结一波,如下图:
在这里插入图片描述

简单的了解一下原型:

  1. 所有的引用类型都拥有__proto__属性(隐式原型),是一个普通的对象
  2. 所有的函数(function)都拥有prototype属性(显式原型),是一个普通对象
  3. 引用类型的__proto__属性指向其构造函数的prototype属性
  4. 在使用原型时,尽量避免在隐式类型上操作

综上所述

function Anima(){}
//函数Anima拥有prototype属性
//引用类型 a 拥有__proto__属性
//由此可得
anima.prototype = {
	printInfo:function(){
		console.log("输出一条语句")
	}
}
let a = new anima()
console.log(a.__proto__ == anima.prototype)  // true
a.printInfo()	// 输出一条语句

解析上面的代码
由于 a 是没有 printInfo 这个属性的,所以就会向其构造函数寻找,如果没有,再到构造函数的原型找该属性,所以就会得到printInfo这个方法;且由上面的代码可得:a的原型是a.proto ,a.proto 等同于 Anima.prototype,即:
在这里插入图片描述
为什么要使用原型

function anima(name,color){
this.name = name
	this.color = color
	this.printInfo = ()=>{
		console.log("name:"+this.name)
	}
}
anima.prototype = {
	printColor: ()=>{
		console.log("color:"+this.color)
	}
}
let a = new anima('aaa','red')
let b = new anima('bbb','green')
let c = new anima('ccc','black')
a.printInfo()
b.printInfo()
c.printInfo()

a.printColor()
b.printColor()
c.printColor()

解析:
如果我们创建了多个Anima对象,那么每创建一次就会创建一个printInfo这个属性,会占用更多的资源,如果在Anima的原型上挂载一个方法printColor,那么printColor只会在Anima这个方法创建时创建,只创建一次。由此可得,使用原型可以更合理的利用资源

理解原型链
所谓原型链,就是一步一步的向上寻找的路线,如下:

function Anima(name,color){
this.name = name
	this.color = color
	this.printInfo = ()=>{
		console.log("name:"+this.name)
	}
}
Anima.prototype = {
	printColor: ()=>{
		console.log("color:"+this.color)
	}
}
let a = new Anima('aaa','red')
let b = new Anima('bbb','green')
let c = new Anima('ccc','black')
a.printInfo()
b.printInfo()
c.printInfo()

a.printColor()
b.printColor()
c.printColor()
//首先,a\b\c都没有toString这个方法,且构造函数Anima也没有这个函数,
//所以就会向上寻找,Anima上面是Object
Object.prototype.toString = function(){
	console.log("name:"+this.name+"---color:"+this.color)
}
a.toString()
b.toString()
c.toString()
// constructor 始终指向创建该对象的构造函数
console.log(a.constructor)	// ƒ Object() { [native code] }
console.log(Anima.constructor) //ƒ Function() { [native code] }

以toString方法为例:a/b/c都没有toString方法,Anima也没有toString方法,再到Anima的上级Object中寻找,Object也没有,就会到其的prototype寻找,由代码可知Object.prototype中有toString这个方法,所以a/b/c能调用toString方法,只不过调用的不是其本身的方法,而是原型链上的方法;总结如下:
在这里插入图片描述
需要注意的是,任何函数的构造函数都是Object,任何原型链最终都会指向null。

综上所述,就得出了文章首的总结图。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值