原型链补充

1.什么是原型对象

函数的独有属性,他用prototype来表示,可以在函数的prototype上挂载一些公用的属性和方法,供实例化对象来访问。

2.__proto__属性

这个属性每一个对象都有,实例化对象就是通过这个属性,来访问原型对象上的属性和方法的。

3.三者之间的关系

1.在构造函数的原型上挂载属性和方法

2.实例化对象上有__proto__可以直接访问,构造函数原型上的属性和方法。

3.代码:

  function Person(naem, age) {
      this.name = name;
      this.age = age;
    }
    Person.prototype.eat=function(){
      console.log('吃饭');
    }

    const a= new Person('小明',20)
    a.eat()  //直接访问原型上的属性和方法

4.例子1

实例化出来的对象能够直接访问,Array.prototype上的属性和方法。

  const arr=new Array(1,2,3)
  arr.reverse()
  console.log(arr);
 console.log(arr.__proto__===Array.prototype)   //返回的结果是True

两层原型:一个是Array.prototype  一个是Object.prototype。

Array.prototype也是一个对象,凡是对象就有__proto__属性,验证他的上一级原型对象是Object.prototype。

代码:

  console.log(Array.prototype.__proto__===Object.prototype);

5.例子2

 class Teacher {
      constructor(name, age) {
        this.name = name;
        this.age = age;
      }
      teach() {
        console.log("教书");
      }
    }
    class Student extends Teacher {
      constructor(name, age) {
        super(name, age);
      }
      learn() {
        console.log("学习");
      }
    }

    const student1 = new Student("小明", 20);
    student1.teach()

    console.log(student1);

验证:

  console.log(student1.__proto__ === Student.prototype, 123456);

    console.log(
      Student.prototype.__proto__ === Teacher.prototype,
      11111111111111111
    );

6.查找规则

1.首先在自己的原型中进行查找

2.没有就往上一级进行查找

3.找不到就返回null

相关推荐

  1. 原型原型

    2024-01-01 08:38:03       53 阅读
  2. 原型原型

    2024-01-01 08:38:03       56 阅读
  3. 原型原型

    2024-01-01 08:38:03       37 阅读
  4. 原型对象、原型原型

    2024-01-01 08:38:03       40 阅读
  5. js 原型原型

    2024-01-01 08:38:03       60 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-01-01 08:38:03       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-01-01 08:38:03       101 阅读
  3. 在Django里面运行非项目文件

    2024-01-01 08:38:03       82 阅读
  4. Python语言-面向对象

    2024-01-01 08:38:03       91 阅读

热门阅读

  1. Anaconda下调用ArcGIS的arcpy工具包

    2024-01-01 08:38:03       65 阅读
  2. 数据挖掘 模糊聚类

    2024-01-01 08:38:03       63 阅读
  3. LeetCode75| 单调栈

    2024-01-01 08:38:03       68 阅读
  4. 一篇文章认识微服务的优缺点和微服务技术栈

    2024-01-01 08:38:03       55 阅读
  5. 九台虚拟机网站流量分析项目启动步骤

    2024-01-01 08:38:03       65 阅读
  6. mac安装yum

    2024-01-01 08:38:03       53 阅读