search
HomeWeb Front-endJS TutorialSummary and answers to JS concept questions

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(&#39;input&#39;);
    button.type = &#39;button&#39;;
    button.value = &#39;Button &#39; + (i + 1);
    button.onclick = function() {
      alert(&#39;Button &#39; + (i + 1) + &#39; clicked&#39;);
    };    document.body.appendChild(button);    document.body.appendChild(document.createElement(&#39;br&#39;));
  }
}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(&#39;input&#39;);
    button.type = &#39;button&#39;;
    button.value = &#39;Button &#39; + (i + 1);    // HERE&#39;S THE FIX:
    // Employ the Immediately-Invoked Function Expression (IIFE)
    // pattern to achieve the desired behavior:
    button.onclick = function(buttonIndex) {      return function() {
        alert(&#39;Button &#39; + (buttonIndex + 1) + &#39; clicked&#39;);
      };
    }(i);    document.body.appendChild(button);    document.body.appendChild(document.createElement(&#39;br&#39;));
  }
}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!

Statement
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
Java vs JavaScript: A Detailed Comparison for DevelopersJava vs JavaScript: A Detailed Comparison for DevelopersMay 16, 2025 am 12:01 AM

JavaandJavaScriptaredistinctlanguages:Javaisusedforenterpriseandmobileapps,whileJavaScriptisforinteractivewebpages.1)Javaiscompiled,staticallytyped,andrunsonJVM.2)JavaScriptisinterpreted,dynamicallytyped,andrunsinbrowsersorNode.js.3)JavausesOOPwithcl

Javascript Data Types : Is there any difference between Browser and NodeJs?Javascript Data Types : Is there any difference between Browser and NodeJs?May 14, 2025 am 12:15 AM

JavaScript core data types are consistent in browsers and Node.js, but are handled differently from the extra types. 1) The global object is window in the browser and global in Node.js. 2) Node.js' unique Buffer object, used to process binary data. 3) There are also differences in performance and time processing, and the code needs to be adjusted according to the environment.

JavaScript Comments: A Guide to Using // and /* */JavaScript Comments: A Guide to Using // and /* */May 13, 2025 pm 03:49 PM

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

See all articles

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 Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Safe Exam Browser

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.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!