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
es6数组怎么去掉重复并且重新排序es6数组怎么去掉重复并且重新排序May 05, 2022 pm 07:08 PM

去掉重复并排序的方法:1、使用“Array.from(new Set(arr))”或者“[…new Set(arr)]”语句,去掉数组中的重复元素,返回去重后的新数组;2、利用sort()对去重数组进行排序,语法“去重数组.sort()”。

JavaScript的Symbol类型、隐藏属性及全局注册表详解JavaScript的Symbol类型、隐藏属性及全局注册表详解Jun 02, 2022 am 11:50 AM

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于Symbol类型、隐藏属性及全局注册表的相关问题,包括了Symbol类型的描述、Symbol不会隐式转字符串等问题,下面一起来看一下,希望对大家有帮助。

原来利用纯CSS也能实现文字轮播与图片轮播!原来利用纯CSS也能实现文字轮播与图片轮播!Jun 10, 2022 pm 01:00 PM

怎么制作文字轮播与图片轮播?大家第一想到的是不是利用js,其实利用纯CSS也能实现文字轮播与图片轮播,下面来看看实现方法,希望对大家有所帮助!

JavaScript对象的构造函数和new操作符(实例详解)JavaScript对象的构造函数和new操作符(实例详解)May 10, 2022 pm 06:16 PM

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于对象的构造函数和new操作符,构造函数是所有对象的成员方法中,最早被调用的那个,下面一起来看一下吧,希望对大家有帮助。

JavaScript面向对象详细解析之属性描述符JavaScript面向对象详细解析之属性描述符May 27, 2022 pm 05:29 PM

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于面向对象的相关问题,包括了属性描述符、数据描述符、存取描述符等等内容,下面一起来看一下,希望对大家有帮助。

javascript怎么移除元素点击事件javascript怎么移除元素点击事件Apr 11, 2022 pm 04:51 PM

方法:1、利用“点击元素对象.unbind("click");”方法,该方法可以移除被选元素的事件处理程序;2、利用“点击元素对象.off("click");”方法,该方法可以移除通过on()方法添加的事件处理程序。

整理总结JavaScript常见的BOM操作整理总结JavaScript常见的BOM操作Jun 01, 2022 am 11:43 AM

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于BOM操作的相关问题,包括了window对象的常见事件、JavaScript执行机制等等相关内容,下面一起来看一下,希望对大家有帮助。

foreach是es6里的吗foreach是es6里的吗May 05, 2022 pm 05:59 PM

foreach不是es6的方法。foreach是es3中一个遍历数组的方法,可以调用数组的每个元素,并将元素传给回调函数进行处理,语法“array.forEach(function(当前元素,索引,数组){...})”;该方法不处理空数组。

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

MinGW - Minimalist GNU for Windows

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.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment