当前位置:网站首页>js 原型和原型链
js 原型和原型链
2022-08-02 03:23:00 【星雨668】
一、前言
今天我们来学习老生常谈的两个问题:原型以及原型链;
什么是原型?
在JavaScript中,原型也是一个对象,通过原型可以实现对象的属性继承,JavaScript的对象中都包含了一个”[[Prototype]]”内部属性,这个属性所对应的就是该对象的原型。
“[[Prototype]]”作为对象的内部属性,是不能被直接访问的。所以为了方便查看一个对象的原型,Firefox和Chrome中提供了__proto__这个非标准(不是所有浏览器都支持)的访问器(ECMA引入了标准对象原型访问器”Object.getPrototype(object)”)。在JavaScript的原型对象中,还包含一个”constructor”属性,这个属性对应创建所有指向该原型的实例的构造函数
首先,来看一段代码:
class Student{
constructor(name,age){
this.name = name;
this.age = age;
}
introduce(){
console.log(`我是${this.name},年龄${this.age}岁`);
}
}
const student = new Student('zhangsan',18);
console.log(student.__proto__); // {constructor: ƒ, introduce: ƒ}
console.log(student.prototype); //undefined
console.log(Student.__proto__); // ƒ () { [native code] }
console.log(Student.prototype); // {constructor: ƒ, introduce: ƒ}
console.log(student.__proto__ === Student.prototype); // true
解读:以上代码是创建一个Student 类,并使用累实例化一个student 实例对象,通过输出对比两者的__ proto__ 和prototype属性;
二、__ proto__和prototype属性
通过上面例子,可以更好的理解以下结论:
1、__ proto__ 属性,也叫隐式原型,它是一个普通的对象,所有引用类型都有该属性(数组,对象,函数);
2、prototype属性,这也叫显式原型,它也是一个普通的对象,是函数所独有的属性。
3、对象的__ proto__属性指向它的构造函数的prototype属性。
什么是原型链
如图:
当实例student,调用introduce()方法时,首先会从自身找;
自身没有时,会通过student.__ proto__到构造函数的原型对象Student.prototype里面找;
如果Student.prototype里没有,就继续往上通过Student.prototype.__ proto__到构造函数原型对象Object.prototype里找,它会一层一层往上找,直到null为止;
这就是原型链,introduce()函数在类Student.prototype中,student.__ proto__ === Student.prototype;所以,实例student能够访问introduce()方法;
在下一篇文章:我们探讨 js proto、prototype、constructor的关系
边栏推荐
- The difference between the knowledge question and answer session with the knowledge
- Phospholipid-Polyethylene Glycol-Aldehyde DSPE-PEG-Aldehyde DSPE-PEG-CHO MW: 5000
- Knowledge Engineering Assignment 2: Introduction to Knowledge Engineering Related Fields
- 第一篇博客
- 微信小程序九宫格抽奖和转盘抽奖的实现
- docker中配置mysql 5.7
- Phospholipid-polyethylene glycol-azide, DSPE-PEG-Azide, DSPE-PEG-N3, MW: 5000
- C语言 十六进制整数字符串转十进制整数
- 1.10今日学习
- SSM integration
猜你喜欢

vue3 访问数据库中的数据

【手把手带你学nRF52832/nRF52840 · (1)开发环境搭建】

DOM manipulation---magnifying glass case

require模块化语法

解决glob()返回文件排序不一致问题&onnx本地按照安装方法

1.8今日学习

C语言入门小游戏—三子棋

ModuleNotFoundError No module named 'xxx' possible solutions

利用 nucleo stm32 f767zi 进行USART+DMA+PWM输入模式 CUBE配置

【 application 】 life many years of operations, what turned scored 12 k + annual bonus salary?
随机推荐
简单黑马头条项目
由中序遍历和前序遍历得到后序遍历(树的遍历)
5.20今日学习
啃瓜记录又一天
函数提升和变量提升
pyppeteer使用样例脚本
C语言 内联函数
ssm various configuration templates
basic operator
Debian 10 NTP Service Configuration
SSM integration
Scientific research reagent DMPE-PEG-Mal dimyristoylphosphatidylethanolamine-polyethylene glycol-maleimide
[Mianjing] Mihayou data development on one side and two sides
COCO数据集训练TPH-YoloV5
vue3 访问数据库中的数据
Redis simple study notes
每日五道面试题总结 22/7/21
枚举法方法:(leetcode1300)转变数组后最接近目标值的数组和
require modular syntax
【装机】老毛桃的安装及使用