JavaScript interview basic knowledge questions sharing
According to a StackOverflow survey, JavaScript is the most popular programming language since 2014. Of course, this is reasonable, after all, 1/3 of development work requires some JavaScript knowledge. Therefore, if you want to become a developer, you should learn this language.
The main purpose of this blog is to summarize common concepts in all interviews so that you can quickly understand them. (In view of the fact that this article is too long to facilitate reading, it will be divided into three blogs for translation. This is the third part. For the first part, please click Quickly Master the Basics of JavaScript Interviews (1))
Recommended related articles:The most complete collection of js interview questions in 2020 (latest)
new keywords
If you use the new
keyword to call a very special form of the function. We call those functions called with new
constructor function.
What exactly does the function using new
do?
Create a new object
Set the prototype of the object to the prototype of the constructor
Execute the constructor,
this
Execute the newly constructed objectReturn the object. If the constructor returns an object, then the constructed object is returned.
// 为了更好地理解底层,我们来定义new关键字 function myNew(constructor, ...arguments) { var obj = {} Object.setPrototypeOf(obj, constructor.prototype); return constructor.apply(obj, arguments) || obj }
What is the difference between using new
and not using it?
function Bird() { this.wings = 2; } /* 普通的函数调用 */ let fakeBird = Bird(); console.log(fakeBird); // undefined /* 使用new调用 */ let realBird= new Bird(); console.log(realBird) // { wings: 2 }
In order to facilitate comparison and understanding, the translator has added an additional test situation:
function MBird(){ this.wings =2; return "hello"; } let realMBrid = new MBird(); console.log(realMBird) // { wings: 2 }
You will find that this sentence return "hello"
does not take effect!
Prototype and inheritance
Prototype (Prototype) is the most confusing concept in JavaScript. One of the reasons is that prototype
can be used in two different situations.
Prototype relationship
Every object has aprototype
object, which contains all the properties of its prototype..__proto__
is an informal mechanism (provided in ES6) used to obtain the prototype of an object. You can understand it as pointing to theparent
of the object.
All ordinary objects inherit the.constructor
property, which points to the constructor of the object. When an object is implemented through a constructor, the__proto__
attribute points to the.prototype
of the constructor's constructor.Object.getPrototypeOf()
is a standard function of ES5, used to get the prototype of an object.Prototype attributes
Each function has a.prototype
attribute, which contains all attributes that can be inherited. By default, this object contains the.constructor
property pointing to the original constructor. Every object created using a constructor has a constructor property.
Let’s use examples to help understand:
function Dog(breed, name){ this.breed = breed, this.name = name } Dog.prototype.describe = function() { console.log(`${this.name} is a ${this.breed}`) } const rusty = new Dog('Beagle', 'Rusty'); /* .prototype 属性包含了构造函数以及构造函数中在prototype上定义的属性。*/ console.log(Dog.prototype) // { describe: ƒ , constructor: ƒ } /* 使用Dog构造函数构造的对象 */ console.log(rusty) // { breed: "Beagle", name: "Rusty" } /* 从构造函数的原型中继承下来的属性或函数 */ console.log(rusty.describe()) // "Rusty is a Beagle" /* .__proto__ 属性指向构造函数的.prototype属性 */ console.log(rusty.__proto__) // { describe: ƒ , constructor: ƒ } /* .constructor 属性指向构造函数 */ console.log(rusty.constructor) // ƒ Dog(breed, name) { ... }
The use of JavaScript can be said to be quite flexible. In order to avoid bugs and not knowing, you might as well connect to Fundebug Online real-time monitoring.
Prototype chain
The prototype chain refers to objects that are linked through prototypes to form a directed chain. When accessing a property of an object, the JavaScript engine will first check whether the object contains the property. If not, check to see if it is included in the object's prototype. And so on until the property is found or the last object is found. The prototype of the last object defaults to null.
Owning vs. Inheriting
An object has two properties, one defined by itself and one inherited.
function Car() { } Car.prototype.wheels = 4; Car.prototype.airbags = 1; var myCar = new Car(); myCar.color = 'black'; /* 原型链中的属性也可以通过in来查看: */ console.log('airbags' in myCar) // true console.log(myCar.wheels) // 4 console.log(myCar.year) // undefined /* 通过hasOwnProperty来查看是否拥有该属性: */ console.log(myCar.hasOwnProperty('airbags')) // false — Inherited console.log(myCar.hasOwnProperty('color')) // true
Object.create(obj)
Create a new object, prototype points to obj
.
var dog = { legs: 4 }; var myDog = Object.create(dog); console.log(myDog.hasOwnProperty('legs')) // false console.log(myDog.legs) // 4 console.log(myDog.__proto__ === dog) // true
Inheritance is pass-by-reference.
Inherited attributes are all in the form of reference. Let's understand it vividly through examples:
var objProt = { text: 'original' }; var objAttachedToProt = Object.create(objProt); console.log(objAttachedToProt.text) // original // 我们更改objProt的text属性,objAttachedToProt的text属性同样更改了 objProt.text = 'prototype property changed'; console.log(objAttachedToProt.text) // prototype property changed // 但是如果我们讲一个新的对象赋值给objProt,那么objAttachedToProt的text属性不受影响 objProt = { text: 'replacing property' }; console.log(objAttachedToProt.text) // prototype property changed
Classic inheritance vs. Prototypal inheritance
Eric Elliott's article has a very detailed introduction: Master the JavaScript Interview: What's the Difference Between Class & Prototypal Inheritance?
The author believes that prototypal inheritance is superior to classic inheritance, and provides a video introduction: https://www.youtube.com/watch...
Asynchronous JavaScript
JavaScript It is a single-threaded programming language, which means that the JavaScript engine can only execute a certain piece of code at a time. The problem it causes is: if a piece of code takes a long time to execute, other operations will be stuck. JavaScript uses Call Stack to record function calls. A Call Stack can be viewed as a stack of books. The last book is placed on top and is removed first. The books placed first are on the bottom and are removed last.
In order to prevent complex code from occupying the CPU for too long, one solution is to define an asynchronous callback function. Let’s define an asynchronous function ourselves:
function greetingAsync(name, callback){ let greeting = "hello, " + name ; setTimeout(_ => callback(greeting),0); } greetingAsync("fundebug", console.log); console.log("start greeting");
我们在greetingAsync
中构造了greeting
语句,然后通过setTimeout
定义了异步,callback
函数,是为了让用户自己去定义greeting的具体方式。为方便起见,我们时候直接使用console.log
。
上面代码执行首先会打印start greeting
,然后才是hello, fundebug
。也就是说,greetingAsync
的回调函数后执行。在网站开发中,和服务器交互的时候需要不断地发送各种请求,而一个页面可能有几十个请求。如果我们一个一个按照顺序来请求并等待结果,串行的执行会使得网页加载很慢。通过异步的方式,我们可以先发请求,然后在回调中处理请求结果,高效低并发处理。
下面通过一个例子来描述整个执行过程:
const first = function () { console.log('First message') } const second = function () { console.log('Second message') } const third = function() { console.log('Third message') } first(); setTimeout(second, 0); third(); // 输出: // First message // Third message // Second message
初始状态下,浏览器控制台没有输出,并且事件管理器(Event Manager)是空的;
first()
被添加到调用栈将
console.log("First message")
加到调用栈console.log("First message")
执行并输出“First message”到控制台console.log("First message")
从调用栈中移除first()
从调用栈中移除setTimeout(second, 0)
加到调用栈setTimeout(second, 0)
执行,0ms之后,second()
被加到回调队列setTimeout(second, 0)
从调用栈中移除third()
加到调用栈console.log("Third message")
加到调用栈console.log("Third message")
执行并输出“Third message”到控制台console.log("Third message")
从调用栈中移除third()
从调用栈中移除Event Loop 将
second()
从回调队列移到调用栈console.log("Second message")
加到调用栈console.log("Second message")
Second message”到控制台console.log("Second message")
从调用栈中移除Second()
从调用栈中移除
特别注意的是:second()
函数在0ms之后并没有立即执行,你传入到setTimeout()
函数的时间和second()
延迟执行的时间并不一定直接相关。事件管理器等到setTimeout()
设置的时间到期才会将其加入回调队列,而回调队列中它执行的时间和它在队列中的位置已经它前面的函数的执行时间有关。
相关学习推荐:javascript视频教程
The above is the detailed content of JavaScript interview basic knowledge questions sharing. For more information, please follow other related articles on the PHP Chinese website!

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

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.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

Atom editor mac version download
The most popular open source editor

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

SublimeText3 English version
Recommended: Win version, supports code prompts!

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.
