


Detailed explanation of JavaScript prototype and prototype chain knowledge points
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.
[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 // }
4. Set the properties and methods on the prototypeThe properties and methods of the prototype can be set in the following two ways:The constructor is automatically added when the function is created, pointing to the constructor itself
- 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 again5.isPrototypeOf() methodEvery object will have aConstructor.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) // 北京市
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 the2. Prototype chainobj
object is the prototype of the
heroobject
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
Finally find the address attribute#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,
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
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:The following figure is a supplement to the top-level prototype that is missing in the first piece of code:{}
.
{}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
3.Object's prototype (Object.prototype)The top-level prototype is 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 classesSo obj.__proto__ is actually Object.prototype,
console.log(obj.__proto__ === Object.prototype) // trueWe can see that the result Object.prototype is the top-level prototype
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)) // 如下长截图所示
- 虽然打印
4.原型链关系内存图
【相关推荐: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!

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Mac version
God-level code editing software (SublimeText3)

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

Dreamweaver CS6
Visual web development tools