Home > Web Front-end > JS Tutorial > Summary and answers to JS concept questions

Summary and answers to JS concept questions

php中世界最好的语言
Release: 2018-06-04 13:49:45
Original
1537 people have browsed it

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"
Copy after login

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??
Copy after login

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! ;-)
Copy after login

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);
Copy after login

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); };
Copy after login

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); };
Copy after login

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!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template