


Detailed explanation of prototype and prototype chain in JavaScript_Basic knowledge
Every object in JavaScript has a built-in attribute prototype. The explanation of the prototype attribute of an object in Javascript is: return a reference to the prototype of the object type. What this means is that the prototype attribute holds a reference to another JavaScript object that serves as the parent object of the current object.
A.prototype = new B();
To understand prototype, you should not confuse it with inheritance. The prototype of A is an instance of B. It can be understood that A has cloned all the methods and properties in B. A can use B's methods and properties. The emphasis here is on cloning rather than inheritance. This situation can occur: A's prototype is an instance of B, and B's prototype is also an instance of A.
Continue to read the analysis below:
Private variables and functions
Variables and functions defined inside a function cannot be accessed by the outside world if no interface is provided to the outside world, that is, the variables and functions are private to the function.
In this way, the variables color and fn cannot be accessed outside the function object Box, and they become private:
var obj = new Box();
alert(obj.color);//pop up undefined
alert(obj.fn);//Same as above
Static variables and functions
When a function is defined and the attributes and functions added by the dot "." are still accessible through the object itself, but its instances cannot be accessed, such variables and functions are called static variables and functions respectively. static function.
Instance variables and functions
In object-oriented programming, in addition to some library functions, we still hope to define some properties and methods at the same time when the object is defined, which can be accessed after instantiation. JS can also do this
Add new methods and properties for instance variables and methods
A and fn are modified in box1, but not changed in box2. Since arrays and functions are both objects and reference types, this means that although the properties and methods in box1 have the same name as those in box2, they have the same name. But it is not a reference, but a copy of the properties and methods defined by the Box object.
This is not a problem for attributes, but it is a big problem for methods, because the methods are doing exactly the same function, but they are copied twice. If a function object has thousands and instances method, then each instance of it must maintain a copy of thousands of methods, which is obviously unscientific. What can we do? Prototype came into being.
Basic concepts
Every function we create has a prototype attribute, which is a pointer to an object. The purpose of this object is to contain properties and methods that can be shared by all instances of a specific type. Then, prototype is the prototype object of the object instance created by calling the constructor.
The advantage of using prototypes is that object instances can share the properties and methods they contain. That is, instead of adding defining object information in the constructor, you can add this information directly to the prototype. The main problem with using constructors is that each method must be created in each instance.
In JavaScript, there are two types of values, primitive values and object values. Every object has an internal property prototype, which we usually call the prototype. The value of the prototype can be an object or null. If its value is an object, the object must also have its own prototype. This forms a linear chain, which we call the prototype chain.
Meaning
Functions can be used as constructors. In addition, only functions have the prototype attribute and can be accessed, but object instances do not have this attribute, only an internal inaccessible __proto__ attribute. __proto__ is a cryptic link in an object to the relevant prototype. According to the standard, __proto__ is not open to the public, which means it is a private property, but the Firefox engine exposes it as a public property that we can access and set externally.
When we call the Bro.run() method, since there is no such method in Bro, he will go to his __proto__ to find it, which is Browser.prototype, so the run() is finally executed. method. (Here, the first letter of a function in capital letters represents a constructor to distinguish it from ordinary functions)
When a constructor is called to create an instance, the instance will contain an internal pointer (__proto__) pointing to the prototype of the constructor. This connection exists between the instance and the prototype of the constructor, not between the instance and the constructor. .
So, now comes the problem. What is the relationship between constructors, instances and prototype objects?
The difference between constructors, instances and prototype objects
Instances are created through constructors. Once an instance is created, it has the constructor attribute (pointing to the constructor) and the __proto__ attribute (pointing to the prototype object),There is a prototype attribute in the constructor, which is a pointer pointing to its prototype object.
There is also a pointer (constructor attribute) inside the prototype object pointing to the constructor: Person.prototype.constructor = Person;
Instances can access properties and methods defined on the prototype object.
Here person1 and person2 are instances, prototype is their prototype object.
Another example:
It can be seen from the program running results that the methods defined on the prototype of the constructor can indeed be called directly through the object, and the code is shared. (You can try removing the prototype attribute in Animal.prototype.behavior and see if it still works.) Here, the prototype attribute points to the Animal object.
Array object instance
Look at an example of an array object. When we create the object array1, the actual object model of array1 in the Javascript engine is as follows:
var array1 = [1,2,3];
The array1 object has a length attribute value of 3, but we can add elements to array1 through the following method:
array1.push(4);
The push method comes from a method (Array.prototye.push()) pointed to by the __proto__ member of array1. It is precisely because all array objects (created through []) contain a __proto__ member that points to the same object (Array.prototype) with push, reverse and other methods that these array objects can use push, reverse and other methods.
Function object instance
function Base() {
This.id = "base"
}
var obj = new Base();
What is the result of this code? The object model we see in the Javascript engine is:
What exactly does the new operator do? It’s actually very simple, it does three things.
var obj = {};
obj.__proto__ = Base.prototype;
Base.call(obj);
Prototype Chain
Prototype chain: When calling a property or method from an object, if the object itself does not have such a property or method, it will go to its associated prototype object to look for it. If the prototype does not have one, it will go to the prototype association. Search for the predecessor prototype, and if there is no more, continue to search for the object referenced by Prototype.Prototype, and so on, until Prototype...Prototype is undefined (Object's Prototype is undefined), thus forming the so-called "prototype chain".
Here, a new entity is created using the constructor Shape(), and then used to override the prototype of the object.
Prototypal inheritance
Prototypal inheritance: At the end of the prototype chain, it is the prototype object pointed to by the prototype attribute of the Object constructor. This prototype object is the ancestor of all objects. This ancestor implements methods such as toString that all objects should inherently have. The prototypes of other built-in constructors, such as Function, Boolean, String, Date and RegExp, are all inherited from this ancestor, but they each define their own properties and methods, so that their descendants show the characteristics of their respective clans. Those characteristics.
In ECMAScript, the way to implement inheritance is to rely on the prototype chain.
Problems with the prototype chain: Although the prototype chain is very powerful and can be used to implement inheritance, it also has some problems. Chief among them comes from value prototypes containing reference types. Prototype properties containing reference types are shared by all instances; this is why properties are defined in the constructor rather than in the prototype object. When inheritance is implemented through prototypes, the prototype actually turns back into an instance of another type. As a result, the original instance properties become prototype properties.
When creating an instance of a subtype, parameters cannot be passed to the constructor of the supertype. In fact, it should be said that there is no way to pass parameters to the constructor of a supertype without affecting all object instances. Coupled with the problems just discussed due to the inclusion of reference type values in prototypes, prototype chains alone are rarely used in practice.
Another example:
Look at the following prototype chain example:
The __ptoto__ attribute (not supported by IE browser) is a pointer from the instance to the prototype object. Its function is to point to the prototype attribute constructor of the constructor. Through these two attributes, you can access the attributes and methods in the prototype. .
Object instances in Javascript are essentially composed of a series of attributes. Among these attributes, there is an internal invisible special attribute - __proto__. The value of this attribute points to the prototype of the object instance, an object. Instances only have a unique prototype.
The difference between __proto__ attribute and prototype attribute
Prototype is a proprietary attribute in the function object.
__proto__ is an implicit attribute of ordinary objects. When new is used, it will point to the object pointed to by prototype;
__ptoto__ is actually an attribute of an entity object, while prototype is an attribute belonging to the constructor. __ptoto__ can only be used in a learning or debugging environment.
Execution process of prototype mode
1. First search for the attributes or methods in the constructor instance, and if there is one, return it immediately.
2. If there is no instance of the constructor, look for it in its prototype object. If there is, return immediately
of the prototype object
To sum up, let’s sort it out:
Factory Mode
function createObject(name,age){
var obj = new Object();
Obj.name = name;
Obj.age = age;
Return obj;
}
The factory pattern solves the problem of large amounts of duplication of instantiated objects, but there is another problem, that is, it is impossible to figure out which object they are instances of.
Using the constructor method not only solves the problem of repeated instantiation, but also solves the problem of object identification.
The difference between using the constructor method and the factory pattern is:
1. The constructor method does not display the created object (new Object());
2. Directly assign properties and methods to this object
3. No return statement
When the constructor is used and new constructor() is used, new Object() is executed in the background;
This in the function body represents the object produced by new Object()
1. To determine whether the property is in the instance of the constructor or in the prototype, you can use the `hasOwnProperty()` function
2. The way literals are created using the constructor attribute will not point to the instance, but to the Object. The way the constructor is created is the opposite
Why points to Object? Because Box.prototype = {}; this way of writing actually creates a new object.
Every time a function is created, its prototype will be created at the same time, and this object will also automatically obtain the constructor attribute
3. If it is an instance method, different instantiations have different method addresses and are unique
4. If it is a prototype method, then their addresses are shared

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.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing


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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

WebStorm Mac version
Useful JavaScript development tools

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Atom editor mac version download
The most popular open source editor