ARTICLE DETAIL

建站实战干货

来自一线的建站与推广经验沉淀,每一条都经过真实交付验证。

原型链补充

2026/10/8 11:21:32 拓冰建站 浏览量
原型链补充

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