当前位置:网站首页>JS中原型和原型链的详细讲解(附代码示例)以及 new关键字具体做了什么的详细讲解
JS中原型和原型链的详细讲解(附代码示例)以及 new关键字具体做了什么的详细讲解
2022-07-31 08:39:00 【道长道长IOT】
这次我们结合实际的案例,来详细的讲解原型和原型链
原型的作用其实一句话概括就是扩展对象
下面我用实际的代码来给大家讲解,详细的注解都在代码里面了
<script>
// 所有的函数都有prototype属性(原型)
function Cat(name,age) {
this.name = name
this.age = age
}
let cat2 = new Cat('喵喵',2)
// Cat构造函数上面并没有eat函数,但是我们可以通过prototype给他挂载一个函数在上面
// 从而使我们接收了实例化的对象的cat2可以调用这个方法
Cat.prototype.eat = function() {
console.log('eat fish');
}
cat2.eat()
// 通过prototype直接格式化时间
let date = new Date()
Date.prototype.formate = function() {
let year = this.getFullYear()
let mouth = this.getMonth() + 1
let day = this.getDate()
return `${
year}年${
mouth}月${
day}日`
}
// 通过一个date.formate直接给你输出这个格式化之后的结果
console.log(date.formate());
//这就是原型扩展对象
所有的对象都有__proto__属性(原型)
// 假如现在有一个对象叫cat,里面有一个属性是name为喵喵
// 现在我们想从喵喵这里面读取一个函数,叫做eat
// 我们可以在cat对象内直接加一个函数eat:fn
// 当然,也可以通过__proto__在他的原型上去挂载
let cat = {
name: '喵喵'
}
cat.__proto__.eat = function (){
console.log('喵喵吃鱼');
}
cat.eat()
</script>
new关键字的作用
function Cat(name,age) {
this.name = name
this.age = age
}
let cat2 = new Cat('喵喵',2)
我们用前面这个例子来进行说明
1.创建一个空对象
//这里的空对象就是new Cat 我们用cat2来接收这个空对象
2.修改this指向,把this指向创建出来的空对象。
//这个时候这个空对象的this就指向cat2,相当于就是 new Cat
3.将空对象的__proto__指向构造函数的prototype
//这里就相当于说现在的cat2可以通过prototype获取原型链上的挂载了的数据或者函数
4.在函数完成之后,返回创建出来的对象(即this)
//返回内容
边栏推荐
- SQL statement knowledge
- Aleo Testnet3规划大纲
- 六、MFC文档类(单文档和多文档)
- Golang-based swagger super intimate and super detailed usage guide [there are many pits]
- 刷题《剑指Offer》day05
- 求职产品经理【九】求职季,如何写好一份简历?
- 哪些字符串会被FastJson解析为null呢
- [MySQL exercises] Chapter 4 · Explore operators in MySQL with kiko
- 【Unity】编辑器扩展-02-拓展Hierarchy视图
- JSP exception对象简介说明
猜你喜欢
随机推荐
ONES 入选 CFS 财经峰会「2022数字化创新引领奖」
【MySQL功法】第4话 · 和kiko一起探索MySQL中的运算符
Ubuntu22.04安装mysql
Ubuntu安装Mysql5.7
求职产品经理【九】求职季,如何写好一份简历?
普通函数的参数校验
【小程序项目开发-- 京东商城】uni-app之自定义搜索组件(中)-- 搜索建议
MySql database optimization query tool
免安装版的Mysql安装与配置——详细教程
TypeError The view function did not return a valid response. The function either returned None 的解决
【小程序项目开发-- 京东商城】uni-app之商品列表页面 (上)
I advise those juniors and juniors who have just started working: If you want to enter a big factory, you must master these core skills!Complete Learning Route!
编译器R8问题Multidex
(C语言基础)原样输入输出
[Mini Program Project Development--Jingdong Mall] Custom Search Component of uni-app (Part 1)--Component UI
功能强大的国产Api管理工具
PowerCLi 一键批量部署OVA 到esxi 7
关于Error EPERM operation not permitted, mkdir...几种解决办法的比较
How on one machine (Windows) to install two MYSQL database
[MySQL exercises] Chapter 4 · Explore operators in MySQL with kiko




![[Yellow ah code] Introduction to MySQL - 3. I use select, the boss directly drives me to take the train home, and I still buy a station ticket](/img/7b/f50c5f4b16a376273ba8cd27543676.png)




