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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

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)

Hot Topics

Java Tutorial
1663
14
PHP Tutorial
1263
29
C# Tutorial
1237
24
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 Evolution of JavaScript: Current Trends and Future Prospects The Evolution of JavaScript: Current Trends and Future Prospects Apr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

JavaScript Engines: Comparing Implementations JavaScript Engines: Comparing Implementations Apr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript: Exploring the Versatility of a Web Language JavaScript: Exploring the Versatility of a Web Language Apr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration) How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration) Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

From C/C   to JavaScript: How It All Works From C/C to JavaScript: How It All Works Apr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration) Building a Multi-Tenant SaaS Application with Next.js (Backend Integration) Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

See all articles