Home Web Front-end JS Tutorial The ultimate detailed explanation of JavaScript prototypes and prototype chains_javascript skills

The ultimate detailed explanation of JavaScript prototypes and prototype chains_javascript skills

May 16, 2016 pm 03:21 PM
javascript prototype javascript prototype chain

The ultimate detailed explanation of JavaScript prototypes and prototype chains

1. Ordinary objects and function objects

In JavaScript, everything is an object! But the objects are also different. It is divided into ordinary objects and function objects. Object and Function are the function objects that come with JS. Here are some examples

function f1(){};
var f2 = function(){};
var f3 = new Function('str','console.log(str)');
var o3 = new f1();
var o1 = {};
var o2 =new Object();
console.log(typeof Object); //function
console.log(typeof Function); //function
console.log(typeof o1); //object
console.log(typeof o2); //object
 console.log(typeof o3); //object
  console.log(typeof f1); //function
  console.log(typeof f2); //function
  console.log(typeof f3); //function 
Copy after login

In the above example, o1 o2 o3 are ordinary objects, and f1 f2 f3 are function objects. How to tell the difference is actually very simple. All objects created through new Function() are function objects, and others are ordinary objects. f1, f2, are all created through new Function() in the final analysis. Function Objects are also created through New Function().

2. Prototype object

In JavaScript, whenever an object (function) is defined, the object will contain some predefined properties. One of the properties of the function object is the prototype object prototype. Note: Ordinary objects do not have prototype, but have __proto__ attribute.

Prototype objects are actually ordinary objects (except Function.prototype, which is a function object, but it is very special. It has no prototype attribute (as mentioned earlier, function objects all have prototype attributes)). Look at the example below:

function f1(){};
console.log(f1. prototype) //f1 {}
console.log(typeof f1. prototype) //Object
console.log(typeof Function. prototype) // Function
console.log(typeof Object. prototype) // Object
console.log(typeof Function. prototype. prototype) //undefined
Copy after login

From the output of this sentence console.log(f1. prototype) //f1 {}, we can see that f1. prototype is an instance object of f1. When f1 is created, an instance object of it is created and assigned to its prototype. The basic process is as follows:

var temp = new f1();
f1. prototype = temp;
Copy after login

So, it is easy to understand why Function.prototype is a function object. As mentioned above, all objects generated by new Function () are function objects, so temp is a function object.

var temp = new Function ();
Function. prototype = temp;
Copy after login

What is the prototype object used for? Mainly used for inheritance. Give an example:

var person = function(name){
  this.name = name
};
person.prototype.getName = function(){
return this.name;
}
var zjh = new person(‘zhangjiahao');
zjh.getName(); //zhangjiahao
Copy after login

从这个例子可以看出,通过给person.prototype设置了一个函数对象的属性,那有person实例(例中:zjh)出来的普通对象就继承了这个属性。具体是怎么实现的继承,就要讲到下面的原型链了。

三.原型链

JS在创建对象(不论是普通对象还是函数对象)的时候,都有一个叫做__proto__的内置属性,用于指向创建它的函数对象的原型对象prototype。以上面的例子为例:

console.log(zjh.__proto__ === person.prototype) //true

同样,person.prototype对象也有__proto__属性,它指向创建它的函数对象(Object)的prototype

console.log(person.prototype.__proto__ === Object.prototype) //true

继续,Object.prototype对象也有__proto__属性,但它比较特殊,为null

console.log(Object.prototype.__proto__) //null

我们把这个有__proto__串起来的直到Object.prototype.__proto__为null的链叫做原型链。如下图:


四.内存结构图

为了更加深入和直观的进行理解,下面我们画一下上面的内存结构图:

画图约定:

疑点解释:

1.Object.__proto__ === Function.prototype // true

Object是函数对象,是通过new Function()创建,所以Object.__proto__指向Function. prototype。

2.Function.__proto__ === Function.prototype // true

Function 也是对象函数,也是通过new Function()创建,所以Function.__proto__指向Function. prototype。

自己是由自己创建的,好像不符合逻辑,但仔细想想,现实世界也有些类似,你是怎么来的,你妈生的,你妈怎么来的,你姥姥生的,……类人猿进化来的,那类人猿从哪来,一直追溯下去……,就是无,(NULL生万物)

正如《道德经》里所说“无,名天地之始”。

3.Function.prototype.__proto__ === Object.prototype //true

其实这一点我也有点困惑,不过也可以试着解释一下。

Function.prototype是个函数对象,理论上他的__proto__应该指向 Function.prototype,就是他自己,自己指向自己,没有意义。

JS一直强调万物皆对象,函数对象也是对象,给他认个祖宗,指向Object. prototype。Object. prototype.__proto__ === null,保证原型链能够正常结束。

五.constructor

原型对象prototype中都有个预定义的constructor属性,用来引用它的函数对象。这是一种循环引用

person.prototype. constructor === person //true
Function.prototype.constructor === Function //true
Object.prototype.constructor === Object //true

Copy after login

完善下上面的内存结构图:

有两点需要注意:

1.注意Object.constructor===Function;//true 本身Object就是Function函数构造出来的
2.如何查找一个对象的constructor,就是在该对象的原型链上寻找碰到的第一个constructor属性所指向的对象

六.总结

1.原型和原型链是JS实现继承的一种模型。

2.原型链的形成是真正是靠__proto__ 而非prototype

要深入理解这句话,我们再举个例子,看看前面你真的理解了吗?

var animal = function(){};
var dog = function(){};
animal.price = 2000;//
dog.prototype = animal;
var tidy = new dog();
console.log(dog. price) //undefined
console.log(tidy.price) // 2000
Copy after login

Why? Draw a memory diagram:


What does this mean? When executing dog.price, it was found that there is no price attribute. Although the animal pointed to by prototype has this attribute, it does not search along this "chain". Similarly, when tidy.price is executed, there is no such attribute, but __proto__ points to animal, and it will search along this chain. Animal has the price attribute, so tidy.price outputs 2000. It follows that the real formation of the prototype chain depends on __proro__, not prototype.

So if dog.__proto__ = animal is specified like this. That dog.price = 2000.

1.

Finally, let me give you a metaphor. Although it is not very accurate, it may be helpful for understanding the prototype.

Father (function object) gave birth to an eldest son (prototype), which is your eldest brother. Your father bought a lot of toys for your eldest brother. When you were born, the family bond between you (__proto__) will make You automatically own your big brother's toys. Similarly, if you have an older son first and buy him a lot of toys, when you have another son, your younger son will naturally have all the toys of your older son. Whether they will fight or not is none of our business.

So, you inherited it from your eldest brother, which proves the saying "A brother is like a father"

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1677
14
PHP Tutorial
1279
29
C# Tutorial
1257
24
Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

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.

JavaScript and the Web: Core Functionality and Use Cases JavaScript and the Web: Core Functionality and Use Cases Apr 18, 2025 am 12:19 AM

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.

JavaScript in Action: Real-World Examples and Projects JavaScript in Action: Real-World Examples and Projects Apr 19, 2025 am 12:13 AM

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.

Understanding the JavaScript Engine: Implementation Details Understanding the JavaScript Engine: Implementation Details Apr 17, 2025 am 12:05 AM

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 vs. JavaScript: Development Environments and Tools Python vs. JavaScript: Development Environments and Tools Apr 26, 2025 am 12:09 AM

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

The Role of C/C   in JavaScript Interpreters and Compilers The Role of C/C in JavaScript Interpreters and Compilers Apr 20, 2025 am 12:01 AM

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.

From Websites to Apps: The Diverse Applications of JavaScript From Websites to Apps: The Diverse Applications of JavaScript Apr 22, 2025 am 12:02 AM

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 vs. JavaScript: Use Cases and Applications Compared Python vs. JavaScript: Use Cases and Applications Compared Apr 21, 2025 am 12:01 AM

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.

See all articles