


4 Methods of Creating Objects in JavaScript Detailed Explanation of Graphic and Text Codes:
1. Factory Mode
Disadvantages: It does not solve the problem of object identification, that is, how to know an object type.
2. Constructor pattern
Compared with factory pattern:
1.No Explicitly create an object
2. Directly assign properties and methods to this object
3. No return statement
To create an instance of person, you must use the new operator, in this way Calling the constructor actually goes through 4 steps:
1. Create a new object
2. Assign the scope of the constructor to the new object
3. Execute the code in the constructor
4. Return a new object
Creating a custom constructor can identify its instance as a specific type.
Disadvantages of the constructor:
Each method is recreated on each instance. Both person1 and person2 have a sayName() method, but the two methods are not the same Function instance. Functions with the same name on different instances are not equal.
There is no need to create two Function instances that complete the same task, and there is also this object. There is no need to bind the function to a specific object before executing the code, as shown below.
Set the sayName attribute to the global sayName function. In this way, since sayName contains a pointer to a function, the person1 and person2 objects share the same function.
However, if the object needs to define many methods, then many global functions must be defined, and there is no encapsulation of custom reference types. In order to solve the above problems, the prototype mode is introduced.
3. Prototype pattern
Understanding prototype objects
Every function we create has a prototype attribute, which is a pointer pointing to An object whose purpose is to contain properties and methods that can be shared by all instances of a specific type. Prototype is the object prototype of the object instance created by calling the constructor. The advantage of using the prototype object is that all object instances can share the properties and methods it contains.
First, the parser will ask the instance person1 whether it has a name attribute, and if so, it will return it.
If not, continue to search for the name attribute in the prototype of person1, and return if there is one.
If not, continue searching in the prototype of person1's prototype.
isPrototypeOf() determines the association between the instance and the prototype object
console.log(Person.prototype.isPrototypeOf(person1)); //true
Object.getPrototypeOf( ) returns the value of [[prototype]]
console.log(Object.getPrototypeOf(person1)); //Person {name: “Yvette”, age: 26, job: “engineer”} 返回的是Person的原型对象。 console.log(Object.getPrototypeOf(person1) === Person.prototype)//true console.log(Object.getPrototypeOf(person1).name);//”Yvette”
hasOwnProperty() method can detect whether a property exists in the instance or in the prototype. Only the given property exists in In the instance, true will be returned.
console.log(person1.hasOwnProperty(“name”));//false
Prototype and in operator
There are two ways to use the in operator: alone and in a for-in loop. When used alone, the in operator returns true if the given property is accessible through the object, whether the property resides in the instance or the prototype.
Use the for in loop to return all enumerable properties that can be accessed through the object, including properties in the instance and properties that exist in the prototype. This will also be returned if a property in the instance masks a non-enumerable property in the prototype. There is a bug in the implementation of versions before IE9. Instance attributes that mask non-enumerable attributes will not be returned in for-in.
There is no log information in the notebook before IE9. Although the toString() method in the person instance blocks the non-enumerable toString() in the prototype;
Prototype abbreviation
This causes person1.constructor to no longer point to Person, but to Object. If the constructor is important, you need to specifically set it to an appropriate value, such as:
But this approach will cause the constructor property to become enumerable.
If you want to set it to be non-enumerable (the default is not enumerable), you can use
Object.defineProperty(Person.prototype, “constructor”, { enumerable: false, value: Person });
The dynamics of the prototype
Since the process of finding a value in the prototype is a search, any modifications we make to the prototype object can be immediately reflected on the instance.
If you rewrite the entire prototype object, the situation is different. When the constructor is called, a [[prototype]] pointer to the original prototype is added to the instance, and modifying the prototype to another object is equivalent to cutting off the connection between the constructor and the original prototype. The pointer in the instance only points to the prototype, not the constructor.
person.prototype points to the original prototype object and does not point to the new prototype object.
Problems with Prototype Objects
The biggest problem with the prototype pattern is caused by its shared nature.
For attributes containing reference type values, the problem is more prominent
The original intention was to modify person1’s friends, but it resulted in the value of person2’s friends attribute Also changed. Therefore we rarely use prototype mode alone.
4. Use the constructor pattern and the prototype pattern in combination
The most common way to create a custom type is to use the constructor pattern and the prototype pattern in combination. The constructor pattern is used to define instance properties, and the prototype pattern is used to define methods and shared properties. In this way, each instance has its own copy of the instance properties and shares references to methods, which saves memory to the maximum extent. .
In addition to the above methods, there are also dynamic prototype mode, parasitic construction mode and safe construction mode, but due to the low frequency of use, they will not be described in detail.
The above is the detailed content of 4 Ways to Create Objects in JavaScript Detailed Graphical Code Explanation. For more information, please follow other related articles on the PHP Chinese website!

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.

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.


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

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

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

Dreamweaver CS6
Visual web development tools

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 Chinese version
Chinese version, very easy to use