当前位置:网站首页>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的关系
边栏推荐
- Phospholipid-polyethylene glycol-targeted neovascularization targeting peptide APRPG, DSPE-PEG-APRPG
- Questions about your resume
- Cloud server installation and deployment of Nacos 2.0.4 version
- Small program van-cell line wrapping can be left-aligned
- 三元判断再三元判断
- 微信小程序云开发之券码领取,怎么防止用户领取到相同的数据?
- 1.13 学习JS
- basic operator
- Living to detect the Adaptive Normalized Representation Learning for GeneralizableFace Anti - Spoofing reading notes
- The querystring module
猜你喜欢
PCL—point cloud data segmentation
1.11今日学习
微信小程序云开发-证件照的实现
我的小笔记 =》原生微信小程序
Chemical reagent Phospholipid-polyethylene glycol-hydroxyl, DSPE-PEG-OH, DSPE-PEG-Hydroxyl, MW: 5000
【手把手带你学nRF52832/nRF52840 · (1)开发环境搭建】
微信小程序九宫格抽奖和转盘抽奖的实现
Circular linked list---------Joseph problem
Phospholipid-polyethylene glycol-thiol, DSPE-PEG-Thiol, DSPE-PEG-SH, MW: 5000
6.24今日学习
随机推荐
page load process
新工程加载YOLOV6的预训练权重问题
The querystring module
每日五道面试题总结 22/7/19
项目中遇到的问题
微信小程序全局组件的定义
面试总结 22/7/25 面试中的重点
我的小笔记 =》原生微信小程序
Common methods of js array deduplication
js 取字符串中某位置某特征的值,如华为(Huawei)=>华为
Amazon sellers how to improve the conversion
相对路径和绝对路径
函数提升和变量提升
C语言 void和void *(无类型指针)
Phospholipid-polyethylene glycol-azide, DSPE-PEG-Azide, DSPE-PEG-N3, MW: 5000
DOM操作---放大镜案例
npm和package.json
ThunderBirde无法登录问题、pycharm调试一直收集数据、RuntimeError: CUDA error: device-side assert triggered等疑难杂症解决
L1-020 帅到没朋友 (20分)
---static page---