This time I will bring you a summary and Q&A of JS concept questions. What are the precautions when using JS concept questions? The following is a practical case, let’s take a look.
Q: Describe inheritance and prototype chain in JavaScript and give examples.
JavaScript is a prototype-based object-oriented language and does not have a traditional class-based inheritance system.
In JS, each object internally refers to an object called prototype, and this prototype object itself also refers to its own prototype object, and so on. This forms a prototype reference chain, and the end of this chain is an object with null as the prototype. JS implements inheritance through the prototype chain. When an object references a property that does not belong to itself, the prototype chain will be traversed until the referenced property is found (or directly found at the end of the chain, in which case the property is not definition).
A simple example:
function Animal() { this.eatsVeggies = true; this.eatsMeat = false; }function Herbivore() {} Herbivore.prototype = new Animal();function Carnivore() { this.eatsMeat = true; } Carnivore.prototype = new Animal();var rabbit = new Herbivore();var bear = new Carnivore();console.log(rabbit.eatsMeat); // logs "false"console.log(bear.eatsMeat); // logs "true"
Q: In the following code snippet, what will alert display? Please explain your answer.
var foo = new Object();var bar = new Object();var map = new Object(); map[foo] = "foo"; map[bar] = "bar"; alert(map[foo]); // what will this display??
Here alert will pop up bar. The JS object is essentially a key-value hash table, where the key is always a string. In fact, when an object other than a string is used as a key, no error occurs. JS will implicitly convert it to a string and use that value as the key.
So, when the map object in the above code uses the foo object as the key, it will automatically call the toString() method of the foo object, and its default implementation will be called here. You will get the string "[object Object]". Then look at the above code and explain it as follows:
var foo = new Object(); var bar = new Object(); var map = new Object(); map[foo] = "foo"; // --> map["[Object object]"] = "foo"; map[bar] = "bar"; // --> map["[Object object]"] = "bar"; // NOTE: second mapping REPLACES first mapping! alert(map[foo]); // --> alert(map["[Object object]"]); // and since map["[Object object]"] = "bar", // this will alert "bar", not "foo"!! // SURPRISE! ;-)
Q: Please explain closures in JavaScript. What is a closure? What unique properties do they have? How and why do you use them? Please give an example.
A closure is a function that contains all variables or other functions that are in scope when the closure is created. In JavaScript, closures are implemented in the form of "inner functions", which are functions defined within the body of another function. Here is a simple example:
(function outerFunc(outerArg) { var outerVar = 3; (function middleFunc(middleArg) { var middleVar = 4; (function innerFunc(innerArg) { var innerVar = 5; // EXAMPLE OF SCOPE IN CLOSURE: // Variables from innerFunc, middleFunc, and outerFunc, // as well as the global namespace, are ALL in scope here. console.log("outerArg="+outerArg+ " middleArg="+middleArg+ " innerArg="+innerArg+"\n"+ " outerVar="+outerVar+ " middleVar="+middleVar+ " innerVar="+innerVar); // --------------- THIS WILL LOG: --------------- // outerArg=123 middleArg=456 innerArg=789 // outerVar=3 middleVar=4 innerVar=5 })(789); })(456); })(123);
An important feature of closures is that the inner function can still access the variables of the outer function even after the outer function returns. This is because, in JavaScript, when functions are executed, they still use the scope that was in effect when the function was created.
However, confusion can result if the inner function accesses the value of the outer function variable when it is called (rather than when it is created). To test the candidate's understanding of this nuance, use the following code snippet, which will dynamically create five buttons and ask the candidate what will be displayed when the user clicks the third button:
function addButtons(numButtons) { for (var i = 0; i < numButtons; i++) { var button = document.createElement('input'); button.type = 'button'; button.value = 'Button ' + (i + 1); button.onclick = function() { alert('Button ' + (i + 1) + ' clicked'); }; document.body.appendChild(button); document.body.appendChild(document.createElement('br')); } }window.onload = function() { addButtons(5); };
Many people will incorrectly answer that when the user clicks the third button, it will show "Button 3 clicked". In fact, the above code contains a bug (based on a misunderstanding of closure) that will display "Button 6 clicked" when the user clicks any of the five buttons. This is because, by the time the onclick method is called (for any button), the for loop has completed and the value of variable i is already 5.
You can next ask the candidate how to fix the error in the above code so that it produces the expected behavior (i.e. clicking button n will display "Button n clicked"). If the candidate can give the correct answer, it means that they know how to use closures correctly, as shown below:
function addButtons(numButtons) { for (var i = 0; i < numButtons; i++) { var button = document.createElement('input'); button.type = 'button'; button.value = 'Button ' + (i + 1); // HERE'S THE FIX: // Employ the Immediately-Invoked Function Expression (IIFE) // pattern to achieve the desired behavior: button.onclick = function(buttonIndex) { return function() { alert('Button ' + (buttonIndex + 1) + ' clicked'); }; }(i); document.body.appendChild(button); document.body.appendChild(document.createElement('br')); } }window.onload = function() { addButtons(5); };
I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related topics on the PHP Chinese website article!
Recommended reading:
How to use li for horizontal arrangement
How to operate the page, visual area, and screen widths High attributes
The above is the detailed content of Summary and answers to JS concept questions. 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

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

Hot Article

Hot Tools

SublimeText3 Chinese version
Chinese version, very easy to use

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

WebStorm Mac version
Useful JavaScript development tools

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.