Home Web Front-end JS Tutorial Seven Questions and Answers to JavaScript Interview Questions That Are Easily Overlooked_Javascript Skills

Seven Questions and Answers to JavaScript Interview Questions That Are Easily Overlooked_Javascript Skills

May 16, 2016 pm 03:15 PM
javascript Interview questions

This question is the last question in a set of front-end interview questions I asked. It is used to test the interviewer's comprehensive JavaScript ability. Unfortunately, in the past two years so far, almost no one can answer it completely. It is not It's difficult just because most interviewers underestimate him.

The topic is as follows:

function Foo() {
 getName = function () { alert (1); };
 return this;
}
Foo.getName = function () { alert (2);};
Foo.prototype.getName = function () { alert (3);};
var getName = function () { alert (4);};
function getName() { alert (5);}

//请写出以下输出结果:
Foo.getName();
getName();
Foo().getName();
getName();
new Foo.getName();
new Foo().getName();
new new Foo().getName();

Copy after login

The answer is:

function Foo() {
 getName = function () { alert (1); };
 return this;
}
Foo.getName = function () { alert (2);};
Foo.prototype.getName = function () { alert (3);};
var getName = function () { alert (4);};
function getName() { alert (5);}

//答案:
Foo.getName();//2
getName();//4
Foo().getName();//1
getName();//1
new Foo.getName();//2
new Foo().getName();//3
new new Foo().getName();//3

Copy after login

This question is based on my previous development experience and various JS pitfalls I encountered. This question involves many knowledge points, including variable definition promotion, this pointer pointing, operator priority, prototype, inheritance, global variable pollution, object attribute and prototype attribute priority, etc.

This question contains 7 questions, please explain them below.

First question

Let’s first look at what was done in the first half of this question. First, we defined a function called Foo, then created a static property called getName for Foo to store an anonymous function, and then created a new prototype object for Foo. An anonymous function called getName. Then a getName function is created through the function variable expression, and finally a getName function is declared.

The first question, Foo.getName, naturally accesses the static properties stored on the Foo function, which is naturally 2. There is nothing to say.

Second question

The second question is to call the getName function directly. Since it is called directly, it is accessing the function called getName in the current scope above, so it has nothing to do with 1 2 3. Many interviewers answered this question as 5. There are two pitfalls here, one is variable declaration promotion, and the other is function expression.

1. Variable declaration improvement

That is, all declared variables or declared functions will be promoted to the top of the current function.

For example, the following code:

console.log('x' in window);//true
var x;
x = 0;
Copy after login

When the code is executed, the js engine will raise the declaration statement to the top of the code and become:

var x;
console.log('x' in window);//true
x = 0;
Copy after login

2. Function expression

var getName and function getName are both declaration statements. The difference is that var getName is a function expression, while function getName is a function declaration. For more information on how to create various functions in JS, you can read the classic JS closure interview questions that most people do wrong. This article has detailed explanations.

The biggest problem with function expressions is that js will split this code into two lines of code and execute them separately.

For example, the following code:

console.log(x);//输出:function x(){}
var x=1;
function x(){}
Copy after login

The actual executed code is to first split var x=1 into two lines: var x; and x = 1;, and then raise the two lines var x; and function x(){} to the top to become:

var x;
function x(){}
console.log(x);
x=1;
Copy after login

So the x declared by the final function covers the x declared by the variable, and the log output is the x function.

Similarly, the final execution of the code in the original question is:

function Foo() {
 getName = function () { alert (1); };
 return this;
}
var getName;//只提升变量声明
function getName() { alert (5);}//提升函数声明,覆盖var的声明

Foo.getName = function () { alert (2);};
Foo.prototype.getName = function () { alert (3);};
getName = function () { alert (4);};//最终的赋值再次覆盖function getName声明

getName();//最终输出4

Copy after login

Third question

The third question, Foo().getName(); first executes the Foo function, and then calls the getName attribute function of the return value object of the Foo function.

The first sentence of the Foo function getName = function () { alert (1); }; is a function assignment statement. Note that it does not have a var declaration, so first look for the getName variable in the current Foo function scope, and there is none. Then look to the upper layer of the current function scope, that is, the outer scope, to find whether it contains the getName variable. It is found, which is the alert(4) function in the second question. Assign the value of this variable to function(){alert(1) }.

Here is actually the getName function in the outer scope that is modified.

Note: If it is still not found here, it will search all the way up to the window object. If there is no getName attribute in the window object, create a getName variable in the window object.

After that, the return value of the Foo function is this, and there are already many articles on the this problem of JS in the blog garden, so I won’t go into more details here.

To put it simply, the point of this is determined by the calling method of the function. In the direct calling method here, this points to the window object.

The Foo function returns the window object, which is equivalent to executing window.getName(), and the getName in the window has been modified to alert(1), so 1 will be output in the end

Two knowledge points are examined here, one is the issue of variable scope and the other is the issue of this pointing.

Question 4

Call the getName function directly, which is equivalent to window.getName(), because this variable has been modified when the Foo function is executed, and the result is the same as the third question, which is 1

Fifth question

The fifth question is new Foo.getName(); , what is examined here is the operator priority issue of js.

By looking up the table above, we can know that the priority of point (.) is higher than the new operation, which is equivalent to:

new (Foo.getName)();
So the getName function is actually executed as a constructor, and 2 pops up.

Question 6

The sixth question is new Foo().getName(). First of all, the operator precedence brackets are higher than new. The actual execution is

(new Foo()).getName()
Then the Foo function is executed first, and Foo, as a constructor, has a return value, so here we need to explain the return value of the constructor in js.

Constructor return value

In traditional languages, constructors should not have a return value. The return value of the actual execution is the instantiated object of this constructor.

In js, constructors can have return values ​​or not.

1. If there is no return value, the instantiated object will be returned as in other languages.

2. If there is a return value, check whether the return value is a reference type. If it is a non-reference type, such as a basic type (string, number, boolean, null, undefined), it is the same as no return value, and its instantiated object is actually returned.

3. If the return value is a reference type, the actual return value is this reference type.

In the original question, this is returned, and this originally represents the current instantiated object in the constructor, so the Foo function finally returns the instantiated object.

Then call the getName function of the instantiated object. Because no attributes are added to the instantiated object in the Foo constructor, we look for getName in the prototype object of the current object and find it.

The final output is 3.

Question 7

The seventh question, new new Foo().getName(); is also an operator priority issue.

The final actual execution is:

new ((new Foo()).getName)();
First initialize the instantiated object of Foo, and then use the getName function on its prototype as the constructor new again.

The final result is 3

Finally

As far as answering questions is concerned, the first question can be answered correctly 100% of the time, the second question can only be answered correctly 50% of the time, the third question can be answered correctly not many, and the fourth question can be answered very, very rarely . In fact, there are not many tricky and bizarre uses for this question. They are all scenarios that you may encounter. Most people with 1 to 2 years of work experience should be completely correct.

I can only say that some people are too impatient and dismissive. I hope everyone can understand some features of js through this article.

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

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)
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

How to use insertBefore in javascript How to use insertBefore in javascript Nov 24, 2023 am 11:56 AM

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

JavaScript and WebSocket: Building an efficient real-time image processing system JavaScript and WebSocket: Building an efficient real-time image processing system Dec 17, 2023 am 08:41 AM

JavaScript is a programming language widely used in web development, while WebSocket is a network protocol used for real-time communication. Combining the powerful functions of the two, we can create an efficient real-time image processing system. This article will introduce how to implement this system using JavaScript and WebSocket, and provide specific code examples. First, we need to clarify the requirements and goals of the real-time image processing system. Suppose we have a camera device that can collect real-time image data

See all articles