search
HomeWeb Front-endJS TutorialSummary of a JavaScript interview question that many front-end programmers often overlook

A summary of a JavaScript interview question that many front-end programmers often overlook:

Preface

I just resigned a few years ago, and I would like to share one of my questions Interview question, this question is the last question in a set of front-end interview questions that I asked. It is used to assess the interviewer’s comprehensive JavaScript ability. Unfortunately, in the past two years so far, there have been almost no It's not that it's difficult for people to answer completely correctly, it's just that most interviewers underestimate them.

The question 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();

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

This question is based on my previous development experience and encounters It is a collection of various pitfalls 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 separately.

First question

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

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

Second question

Second question, 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;

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;

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 details on how to create various functions in JS, see the article "Classic JS Closure Interview Questions Most People Do Mistakenly."

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(){}

The actual executed code is, first split var x=1 into var x; and x = 1; two lines, 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;

So the final function declaration x 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

The third question

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

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 scope of the current Foo function. There is no . Then look to the upper layer of the current function scope, that is, the outer scope, to see if it contains the getName variable. We found it, 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 eventually be output. Two knowledge points were investigated here, one is the variable scope issue, and the other is the this pointing issue.

Fourth question

Directly calling the getName function is equivalent to window.getName(). Because this variable has been modified by the Foo function when it is executed, the result is the same as the third question, which is 1

Fifth question

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

js operator priority:

Summary of a JavaScript interview question that many front-end programmers often overlook

Reference link: http://www.php.cn/

By looking up the table It can be known that the priority of dot (.) is higher than the new operation, which is equivalent to:

new (Foo.getName)();

So the getName function is actually executed as a constructor , then 2 pops up.

第六问

第六问 new Foo().getName() ,首先看运算符优先级括号高于new,实际执行为

(new Foo()).getName()

遂先执行Foo函数,而Foo此时作为构造函数却有返回值,所以这里需要说明下js中的构造函数返回值问题。

构造函数的返回值

在传统语言中,构造函数不应该有返回值,实际执行的返回值就是此构造函数的实例化对象。

而在js中构造函数可以有返回值也可以没有。

1、没有返回值则按照其他语言一样返回实例化对象。

Summary of a JavaScript interview question that many front-end programmers often overlook1

2、若有返回值则检查其返回值是否为引用类型。如果是非引用类型,如基本类型(string,number,boolean,null,undefined)则与无返回值相同,实际返回其实例化对象。

Summary of a JavaScript interview question that many front-end programmers often overlook2

3、若返回值是引用类型,则实际返回值为这个引用类型。

Summary of a JavaScript interview question that many front-end programmers often overlook3

原题中,返回的是this,而this在构造函数中本来就代表当前实例化对象,遂最终Foo函数返回实例化对象。

之后调用实例化对象的getName函数,因为在Foo构造函数中没有为实例化对象添加任何属性,遂到当前对象的原型对象(prototype)中寻找getName,找到了。

遂最终输出3。

第七问

第七问, new new Foo().getName(); 同样是运算符优先级问题。

最终实际执行为:

new ((new Foo()).getName)();

先初始化Foo的实例化对象,然后将其原型上的getName函数作为构造函数再次new。

遂最终结果为3

最后

就答题情况而言,第一问100%都可以回答正确,第二问大概只有50%正确率,第三问能回答正确的就不多了,第四问再正确就非常非常少了。其实此题并没有太多刁钻匪夷所思的用法,都是一些可能会遇到的场景,而大多数人但凡有1年到2年的工作经验都应该完全正确才对。

只能说有一些人太急躁太轻视了,希望大家通过此文了解js一些特性。

并祝愿大家在新的一年找工作面试中胆大心细,发挥出最好的水平,找到一份理想的工作。


The above is the detailed content of Summary of a JavaScript interview question that many front-end programmers often overlook. 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
JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 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.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 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.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 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.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

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

Video Face Swap

Video Face Swap

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

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)