Home >Web Front-end >JS Tutorial >Detailed explanation of JavaScript prototype and prototype chain knowledge points

Detailed explanation of JavaScript prototype and prototype chain knowledge points

WBOY
WBOYforward
2022-07-06 13:44:572285browse

This article brings you relevant knowledge about javascript, which mainly organizes issues related to prototypes and prototype chains, including the concept of prototypes, the constructor attribute on function prototypes, and the prototype chain Understanding and so on, let’s take a look at it below, I hope it will be helpful to everyone.

Detailed explanation of JavaScript prototype and prototype chain knowledge points

[Related recommendations: javascript video tutorial, web front-end

1. Prototype

1. Concept

In JavaScript, a function is an object of type Function that contains properties and methods. The prototype (Prototype) is an attribute of the Function type object.

The prototype attribute is included when the function is defined, and its initial value is an empty object. There is no prototype type defined for functions in JavaScript, so the prototype can be of any type.

The prototype is used to save the shared properties and methods of the object. The properties and methods of the prototype do not affect the properties and methods of the function itself.

// Function类型的属性->所有函数都具有的属性
console.log(Function.prototype);//[Function]

// 定义函数
function fn() {
    console.log('this is function');
}

//原型的默认值是空对象
console.log(fn.prototype);//fn {}

// 函数包含构造函数 ——> 所有引用类型其实都是构造函数
console.log(Number.prototype); //[Number: 0]

console.log(Object.prototype);//{}

2. Get the prototype

You can get the prototype of the object in the following two ways to set shared properties and methods:

    Through the
  • prototype attribute of the constructor
  • Through the
  • getPrototype(obj) method of the Object object.
function fn() {
    console.log('this is function');
}

//使用访问对象的属性语法结构
console.log(fn.prototype);//fn {}
console.log(fn['prototype']);//fn {}

//Object类型提供getPrototypeOf()方法
console.log(Object.getPrototypeOf(fn));//[Function]

#3. Understand the constructor attribute on the function prototype

Object.getOwnPropertyDescriptors() The method is used to get a Descriptors for all of the object's own properties.

var result = Object.getOwnPropertyDescriptor(Object.prototype,'constructor');
console.log(result) //输出结果如下:
//{
//   value: [Function: Object],
//   writable: true,
//   enumerable: false,
//   configurable: true
// }

The constructor is automatically added when the function is created, pointing to the constructor itself

4. Set the properties and methods on the prototype

The properties and methods of the prototype can be set in the following two ways:

    The properties and methods of the prototype are defined separately.
构造函数.prototype.属性名 = 属性值 ;构造函数.prototype.方法名 = function(){} ;
    Define a new object directly for the prototype.
When we need to add many attributes to the prototype, it is too troublesome to write over and over again

Constructor.prototype.Attribute name, you can directly modify the entire prototype

构造函数.prototype = {
    属性名:属性值,
    方法名:function(){}}
function foo () {}foo.prototype = {
    constructor: foo,
    name: 'jam',
    age: 18,
    address: '北京市'}var fn = new foo()console.log(fn.address) // 北京市
5.isPrototypeOf() method

Every object will have a

isPrototypeOf() method, which uses To determine whether an object is the prototype of another object.

示例代码如下:
// 通过初始化器方式定义对象
var obj = {
    name:'jam'
}
// 定义构造函数
function Hero() {}
// 将对象obj赋值给构造函数Hero的原型
Hero.prototype = obj;
// 通过构造函数创建对象
var hero = new Hero();

// isPrototypeOf()方法判断指定对象是否是另一个对象的原型
var result = obj.isPrototypeOf(hero);
console.log(result);//true
Verified that the

obj object is the prototype of the hero object

2. Prototype chain

1. Understanding of the prototype chain

Next we use a piece of code to expand our understanding of the prototype chain:

场景:查找obj对象身上的address属性
js执行的步骤:
    1. 会触发get操作
    2. 在当前的对象中查找属性
    3. 如果没有找到,这个时候会去原型链(__proto__)对象上查找
       1. 查找到结束
       2. 没查找到一直顺着原型链查找,直到查找到顶层原型(顶层原型是什么暂时卖个关子)
1.1 The sample code is as follows:

var obj = {
    name: 'jam',
    age: 19
}
/* 
    要求:查找obj对象身上的address属性
*/

// 原型链一层一层向上查找,如果一直没有找到,直到查找到顶层原型结束
obj.__proto__ = {}
obj.__proto__.__proto__ = {}
obj.__proto__.__proto__.__proto__ = {
    address: '北京市'
}

console.log(obj.address) // 北京市
console.log(obj.__proto__.__proto__.__proto__)  // { address: '北京市' }

1.2 Memory graph

Detailed explanation of JavaScript prototype and prototype chain knowledge points

Finally find the address attribute


Then there is a problem here. If it is not found, it will go endlessly. Looking for it? Next, let’s take a look at

#2. What is the top-level prototype?

As we mentioned above, we will not search endlessly along the prototype chain. When the top-level prototype is found, if it has not been found yet,

undefined will be returned.

So what is the top-level prototype? The sample code is as follows:

var obj = { name: 'jam' }console.log(obj.__proto__)  // {}console.log(obj.__proto__.__proto__)  // null
The prototype of the literal object obj is:

{}. {} is the top-level prototype When we continue to print
__proto__, a null value is returned, which proves that the upper layer is already the top-level prototype

The following figure is a supplement to the top-level prototype that is missing in the first piece of code:


Detailed explanation of JavaScript prototype and prototype chain knowledge points

The top-level prototype is Object.prototype

3.Object's prototype (Object.prototype)

3.1 So where is the end of the prototype chain? For example, does the third object also have the prototype__proto__ attribute?

var obj = {name:'jam'}obj.__proto__ = {}obj.__proto__.__proto__ = {}obj.__proto__.__proto__.__proto__ = {}console.log(obj.__proto__.__proto__.__proto__.__proto__)  // {}
We found that the above printed result is

empty object {}

    In fact, this prototype is our top-level prototype
var obj = {
  name: 'jam',
  age: 19
  }
  console.log(obj.__proto__)  // {}
  console.log(Object.prototype) // {}
  console.log(obj.__proto__ === Object.prototype) // true
  • Object is the parent class of all classes

    So obj.__proto__ is actually Object.prototype,

    console.log(obj.__proto__ === Object.prototype) // true We can see that the result Object.prototype is the top-level prototype

  • The prototypes of objects created directly from Object are
  • {}
  • 3.2 Then we may ask: {}What is special about the prototype?

    • 特殊点1:该对象有原型属性,但是它的原型属性已经指向的是null,也就是已经是顶层原型了;
      console.log(obj.__proto__.__proto__.__proto__.__proto__.__proto__) // null
    • 特殊点2:该对象上有甚很多默认的属性和方法;
      • 虽然打印Object.prototype的结果为空对象{},但它不是空的,只是里面的属性不可枚举而已,例如我们就打印constructor属性看看
        <!-- 可以看出是有constructor属性的 ,并不是空的-->console.log(Object.prototype.constructor)  // [Function: Object]  <!-- constructor 指回了Object -->
      • 我们也可以通过Object.getOwnPropertyDescriptors()方法获取Object.prototype中的所有自身属性的描述符。
        console.log(Object.getOwnPropertyDescriptors(Object.prototype)) // 如下长截图所示
        Detailed explanation of JavaScript prototype and prototype chain knowledge points

    4.原型链关系内存图

    Detailed explanation of JavaScript prototype and prototype chain knowledge points

    【相关推荐:javascript视频教程web前端

    The above is the detailed content of Detailed explanation of JavaScript prototype and prototype chain knowledge points. For more information, please follow other related articles on the PHP Chinese website!

    Statement:
    This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete