Home Web Front-end JS Tutorial A common web front-end interview question that is often looked down upon (JS)_javascript skills

A common web front-end interview question that is often looked down upon (JS)_javascript skills

May 16, 2016 pm 03:15 PM
Front-end interview questions

Interview questions are a topic that both recruiting companies and developers are very concerned about. Companies hope to use them to understand the developers’ true level and ability to handle details, while developers hope to be able to demonstrate their level to the greatest extent (even perform beyond the norm). This article provides many front-end development interview questions, which are worth reading for both recruiters and applicants!

Foreword

I just resigned a few years ago. I would like to share with you an interview question I once asked. This question is the last question in a set of front-end interview questions I asked. It is used to assess the interviewer's comprehensive JavaScript ability. It is a pity. In the nearly two years so far, almost no one has been able to answer it completely. It is not that it is difficult but 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 the various pitfalls I encountered in JS. 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 we did in the first half of this question. We first 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.

Variable declaration promotion

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

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.

Fourth question

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

Fifth question

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

js operator precedence:

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 issue of the constructor in js.

The return value of the constructor

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 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)

What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

Who gets paid more Python or JavaScript? Who gets paid more Python or JavaScript? Apr 04, 2025 am 12:09 AM

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

How to merge array elements with the same ID into one object using JavaScript? How to merge array elements with the same ID into one object using JavaScript? Apr 04, 2025 pm 05:09 PM

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

The difference in console.log output result: Why are the two calls different? The difference in console.log output result: Why are the two calls different? Apr 04, 2025 pm 05:12 PM

In-depth discussion of the root causes of the difference in console.log output. This article will analyze the differences in the output results of console.log function in a piece of code and explain the reasons behind it. �...

TypeScript for Beginners, Part 2: Basic Data Types TypeScript for Beginners, Part 2: Basic Data Types Mar 19, 2025 am 09:10 AM

Once you have mastered the entry-level TypeScript tutorial, you should be able to write your own code in an IDE that supports TypeScript and compile it into JavaScript. This tutorial will dive into various data types in TypeScript. JavaScript has seven data types: Null, Undefined, Boolean, Number, String, Symbol (introduced by ES6) and Object. TypeScript defines more types on this basis, and this tutorial will cover all of them in detail. Null data type Like JavaScript, null in TypeScript

How to achieve parallax scrolling and element animation effects, like Shiseido's official website?
or:
How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? How to achieve parallax scrolling and element animation effects, like Shiseido's official website? or: How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? Apr 04, 2025 pm 05:36 PM

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

Can PowerPoint run JavaScript? Can PowerPoint run JavaScript? Apr 01, 2025 pm 05:17 PM

JavaScript can be run in PowerPoint, and can be implemented by calling external JavaScript files or embedding HTML files through VBA. 1. To use VBA to call JavaScript files, you need to enable macros and have VBA programming knowledge. 2. Embed HTML files containing JavaScript, which are simple and easy to use but are subject to security restrictions. Advantages include extended functions and flexibility, while disadvantages involve security, compatibility and complexity. In practice, attention should be paid to security, compatibility, performance and user experience.

See all articles