当前位置:网站首页>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的关系
边栏推荐
- js takes the value of a feature at a certain position in the string, such as Huawei=> Huawei
- 微信小程序实现文本安全监测
- DSPE-PEG-Silane, DSPE-PEG-SIL, phospholipid-polyethylene glycol-silane modified active group
- display,visibility,opacity
- 猴子选大王(约瑟环问题)
- meime模块
- require modular syntax
- 新工程加载YOLOV6的预训练权重问题
- 面试总结 22/7/25 面试中的重点
- 环形链表---------约瑟夫问题
猜你喜欢
随机推荐
nucleo stm32 h743 FREERTOS CUBE MX配置小记录
js 取字符串中某位置某特征的值,如华为(Huawei)=>华为
STM32 CAN过滤器
---static page---
ImportError: libGL.so.1: cannot open shared object file: No such file or directory
每日五道面试题总结 22/7/20
SSM integration
FreeRTOS内核详解(1) —— 临界段保护原理
C语言的变长数组
URL模块
简单黑马头条项目
Scientific research reagent DMPE-PEG-Mal dimyristoylphosphatidylethanolamine-polyethylene glycol-maleimide
SOCKS5
1.13 学习JS
微信小程序九宫格抽奖和转盘抽奖的实现
每日五道面试题总结 22/7/21
4.14到新公司的一天
1.uview form校验位置可以改变 2.时间区间
网址URL
basic operator