1. The following objects are known, please design an example of property interception read operation based on the proxy method of es6
When the implementation is required to access a property that does not exist in the target object example, an error is thrown: Property "$(property)" does not exist (2018 Toutiao)
// 案例代码
const man = {
name: 'jscoder',
age: 22
}
//补全代码
const proxy = new Proxy(...)
proxy.name // "jscoder"
proxy.age // 22
proxy.location // Property "$(property)" does not exist
Reply:
const proxy = new Proxy(main, {
get (target, property) {
if (property in target) {
return target[property];
} else {
throw Error(`Property "${property}" does not exist`)
}
}
});
2. The red light is on once every three seconds, the green light is on once every second, and the yellow light is on once every 2 seconds.
To implement a function, how to make the three lights alternately and repeatedly turn on? (implemented by Promise) The three lighting functions already exist:
function red() {
console.log('red')
} // 3秒
function green() {
console.log('green')
} // 1秒
function yellow() {
console.log('yellow')
} // 2秒
Reply:
const timerFn = function (times, callback) {
return new Promise((resolve, reject) => {
setTimeout(() => {
callback();
resolve();
}, times);
});
};
async function repeatLights () {
await timerFn(3000, red);
await timerFn(1000, green);
await timerFn(2000, yellow);
repeatLights();
}
repeatLights();
3. Write the console print results in order (Country Garden 2020)
var User = {
count:1,
action:{
getCount:function () {
return this.count
}
}
}
var getCount = User.action.getCount;
setTimeout(() => {
console.log("result 1",User.action.getCount())
})
console.log("result 2",getCount())
Reply:
result 2 undefined
result 1 undefined
4. Short answer (two sides of byte beating)
- What do you think is the difference between typescript and javascript
- What types of typescript have you used
- The difference between type and interface in typescript
Reply:
(1) TS is a superset (extension set) of JS, which is based on JS with more extended features, including: powerful type system, good support for ES6+, TS will eventually be compiled into JS for execution
- Both JS and TS are concrete implementations of ECMAScript
- TS is static type, and JS is dynamic type
- TS extends JS and fully embraces JS
- TS needs to be compiled, JS does not need to be compiled (unless it needs to be compatible with the lower version operating environment)
- JavaScript was first introduced by Netscape and is now mainly implemented by major browser vendors
- And TypeScript is currently designed and maintained by Microsoft
(2) Primitive type: string / number / boolean / null / void / symbol
Array type, object type, function type, primitive ancestor, enum enum, any type, Void type, interface, class, generic
(3) The difference between type and interface in typescript
Type and interface are the same:
- Can describe an object or function
- Both can realize the function of extensions, interface extends interface, type is extended through cross type
The difference between type and interface:
- type can declare basic type aliases, union types, tuples and other types, but interface cannot;
- Interface can declare merge, but type cannot;
- Generally speaking, when defining a type, use interface if it can be implemented with interface, and use type if it cannot.
5. Understanding of async/await and analysis of internal principles
Reply:
- Async/await is actually the syntactic sugar of generator generator. Its appearance makes it easier and more convenient for us to write asynchronous code. It can avoid writing complicated generator functions. There is no callback function in asynchronous code. The syntax is just like synchronous code. Asynchronous programming is a perfect solution.
- Internal principle: The internal use of promise and generator to achieve. await needs to be used with async, just like yield needs to be used with
function * main () { ... }
, yield can be followed by a promise instance, and the main function can be executed to get a generator instance g. You can useg.next()
to control the execution order of the internal code of the main function , Withg.next().value.then()
andg.next().done
can achieve the effect of async/await.
6. Async/await What should I do if there is an error in the execution of the method on the right? (Baidu One Side 2020)
Reply:
// 可以通过 try catch 来捕获错误
async function main () {
try {
const articles = await ajax('/api/articles.json');
} catch (error) {
console.log(error);
}
}
7. Tell me about the event loop process? When is the function passed in when the promise is defined execute? (Three sides of millet)
Reply:
- js is single-threaded and can only do one thing at the same time. Two pieces of JS cannot be executed at the same time. The main reason is to avoid conflicts in DOM rendering. The solution is to be asynchronous, and the code written asynchronously is not executed in accordance with the written method, and there are too many callbacks, which leads to poor readability and incomprehensibility, so promise / async await appears.
- event-loop refers to event polling, which is a specific solution for js to achieve asynchronous. Synchronous code, directly executed in the main thread (Call stack), push-pop stack. Asynchronous tasks will be placed in the message queue (Queue) in turn, EventLoop will monitor the call stack and message queue, when the code in the call stack is executed, it will take the first task in the message queue and put it on the call stack for execution. And so on.
- The function passed in when the promise is defined will be executed at the end of this call stack.
8. Talk about the application scenarios of the anti-shake function, and briefly talk about the implementation method (Didi)
Reply:
Anti-shake function
- Application scenarios of the anti-shake function: Anti-shake means that the function can only be executed once within n seconds after the event is triggered. If the event is triggered again within n seconds, the function execution time will be recalculated. Common scenarios include: input event anti-shake during keyboard input and real-time search, browser window change resize event anti-shake, etc. (page scroll events, mouse movement events).
- Implementation method: use closure and setTimeout to achieve, create a debounce function, define a timer variable to save the timer, return a function, and manage the execution timing of the timer and fn in the function.
Throttle function
- The application scenario of the throttling function: throttling means that the same event is triggered continuously within a continuous period of time, and the event will be executed only once every n seconds. Common scenarios include: lazy loading needs to monitor and calculate the position of the scroll bar, and the user can only click the submit button once within a certain period of time, and so on.
- Implementation method: Use closure and setTimeout with an identifier to implement, create a throttle function, define a canRun variable to save whether the task is executable, return a function, and manage the value of canRun and the execution timing of fn in the function , And return directly when canRun is false.
9. Talk about the garbage collection mechanism of V8 (Xiaomi)
Reply:
V8 is a mainstream JavaScript execution engine that uses real-time compilation and is very fast; memory is limited, the maximum is 1.5G for 64-bit operating systems, and the maximum for 32-bit operating systems is 800M. The garbage collection mechanism is used to release memory. Using the idea of generational collection, the memory is divided into the young generation and the old generation, and different algorithms are used for garbage collection for different objects.
The new generation object recycling implementation:
- The recycling process adopts a copy algorithm + tag sorting
- The new generation memory is divided into two equal-sized spaces From and To
- The used space is From, and the free space is To
- The active objects are stored in the From space, and the active objects are copied to the To after marking
- Complete memory release after swapping space between From and To
The old generation object recycling implementation:
- Mainly use mark removal, mark sorting, and incremental mark algorithms
- First use the mark to clear the garbage space to complete the recycling
- Use tagging to optimize space
- Use incremental marking for efficiency optimization
10. What indicators in the performance API can measure the time to the first screen
Reply:
performance.timing returns a PerformanceTiming object, which includes performance information related to the page. For example: performance.timing.navigationStart represents the time when the page starts to load. You can subtract the navigationStart from the time when the first screen is loaded to get the first screen time.
11. What role does the temporary dead zone play in the new features of EcmaScript?
Reply:
- ES6 stipulates that if there are let and const commands in a block, the variables declared by these commands in this block form a closed scope from the beginning. If you use these variables before the declaration, an error will be reported, which is called a temporary dead zone grammatically.
- ES6 stipulates that the temporary dead zone and let and const statements do not have variable promotion, mainly to reduce runtime errors and prevent the variable from being used before the variable declaration, which leads to unexpected behavior. Such mistakes are very common in ES5, and now with this kind of regulation, it is easy to avoid such mistakes.
12. The difference between the observer model and the publish-subscribe model
Reply:
- Observer mode: Observer-Watcher, there is an update() method, which is the specific thing to do when the event occurs; target-Dep, subs array -> store all observers, addSub() -> add Observer, notify() -> when an event occurs, call the update() method of all observers; there is no signal center
- Publish and subscribe mode: Assuming that there is a "signal center", a certain person will "publish" a signal to the signal center when the execution is completed, and other tasks can "subscribe" to the signal center to know when You can start execution yourself.
- The observer mode is scheduled by a specific target. For example, when an event is triggered, Dep will call the observer's method, so there is a dependency between the subscriber and the publisher of the observer mode;
- The publish-subscribe mode is called by the unified dispatch center, so publishers and subscribers do not need to know the existence of each other, and there is no direct dependency between the two
13. Did gulp write tasks by himself? Talk about its construction process (Ali 2018)
Reply:
I have written some small demos using gulp, but haven't used them in production projects.
The construction process of gulp:
- Create gulpfile.js file, the entry file of gulp
- Create and export a build task through
exports.foo = done => {...}
- In the task, the file stream is read through the gulp.src function, and the file stream is processed and converted with the pipe() method of the file stream (handed over to the plug-in for processing or output to the specified file), and finally through the gulp.dest() method The conversion result stream is output to the target location
- Then after processing, the execution result is returned to end the execution of a task
- By
gulp.series
creating a serial task, bygulp.parallel
create parallel tasks - Gulp also supports asynchronous tasks, which can be used with promise and async to create tasks
- Finally, export the created task through exports, and then you can run the defined gulp task
gulp foo
- The core principle of the gulp construction process: input => processing => output, read stream => conversion stream => write stream
14. What is the role of package-lock.json, what will happen if it is not in the project, give an example
Reply:
Package-lock.json function:
Used to lock the version number and address of the package during installation to ensure that the version of the dependent package downloaded by project members during npm install is the same.
If there is no package-lock.json in the project, but there is a dependency package "lodash": "^4.17.4"
, only the major version can be locked at this time, and the latest version under that major version is pulled each time you install. But for the stability of the project, we should not arbitrarily upgrade dependent packages, which may lead to unpredictable risks and workloads such as adaptation testing.
15. What are the common configuration items of webpack, and explain their purpose (learn from 2020)
Reply:
module.exports = {
mode: 'none', // 打包模式, none development production
entry: './src/main.js', // 打包入口文件
output: {
filename: 'bundle.js',
path: path.join(__dirname, 'dist') // 打包出口
},
devServer: {}, // 配置 devServer contentBase proxy 等
devtool: 'source-map', // 配置 source-map 有 12 中模式可选择
module: {}, // 配置处理转换文件的各种 loader
plugins: [], // 配置打包过程使用的插件 copy-webpack-plugin html-webpack-plugin 等等
optimization: {} // 用于优化打包结果的配置 压缩代码 tree-shaking 移除冗余代码等
}
16. Explain the role and principle of webpack css-loader? (Learn from whom)
Reply:
- Function: css-loader will process @import and url() for loading .css files, just like js parsing import/require().
- Principle: By default, webpack only parses the js code. The css-loader will read and parse the css code in the .css file into a string, so that we can parse and apply the css code during the packaging process. Usually used with style-loader, it will mount the content parsed by css-loader to the style tag of the html page.
17. What is the difference between loader and plugin in webpack (ByteDance Sohu)
Reply:
- Loader focuses on the conversion and loading of resource modules (compilation and conversion code, file operation, code inspection)
- plugin solves other automation tasks (clearing the dist directory before packaging, copying static files, compressing code, etc.)
18. What are the pros and cons of webpack, rollup, and parcel?
Reply:
webpack
- Advantages: Complete ecology, almost all packaging needs can be achieved with various plug-ins, now the most popular packaging tool for front-end applications
- Disadvantages: The documentation is more complicated, the configuration is more cumbersome, and there is a certain learning cost; the packaged build result has a lot of code that the module depends on, and the packaged result is large
rollup
- Advantages: rollup is very small, just an ESM packager, the output result is flatter, unreferenced code will be automatically removed, and the packaged result is still fully readable
- Disadvantages: It is more complicated to load non-ESM third-party modules; the modules are finally packaged into a function, which cannot realize HMR; in the browser environment, the code splitting function depends on AMD
parcel
- Advantages: Zero-configuration front-end application packager, fast construction speed, and automatic installation of dependencies.
- Disadvantages: The ecology is not perfect, and it is not conducive to extension plug-ins. It is its disadvantage.
19. What is the difference between babel.config.js and .babelrc?
Reply:
- The configuration file of .babelrc is folder-specific, that is, the folder where the configuration file is located, including subfolders, will apply the settings of this configuration file, and the lower-level configuration file will overwrite the upper-level configuration file, this way can be set for different directories Different rules.
- babel.config.js is written in the same way as .babelrc, but babel.config.js is for the entire project, and only one project is placed in the project root directory.
- The .babelrc file in the project root directory has the same effect as babel.config.js. If both types of configuration files exist, .babelrc will overwrite the configuration of babel.config.js
20. What is the purpose and principle of tree shaking in webpack?
Reply:
- Tree-shaking Purpose: Remove unreferenced code in JS, merge all modules into one function as much as possible, improve code operation efficiency, and reduce code size
- Tree-shaking principle: Use the import and export in ES2015 to find unreferenced export codes or modules, and remove them from the packaging results
21. Explain the principle of eventbus, and describe the practice of eventbus in vue (ape tutoring)
Reply:
- Principle: EventBus event bus. In Vue, you can use EventBus as a communication bridge (component communication), which means that all components share the same event center, which can be registered to send events or receive events, and all components can flexibly notify other components.
- Application practice: communication between brother components and communication between unrelated components. For example, you modify a variable in a component and you want to listen to the change of this variable in other components. EventBus.$emit() is used to create a release Event, EventBus.$on() is used to subscribe to events, EventBus.$off() is used to unsubscribe events
22. What is the implementation principle of vue-loader
Reply:
- vue-loader is a webpack loader, which allows us to write vue components in a single file component format. The components are generally divided into three modules <template> <script> <style>
- It is allowed to use other webpack loaders for each part of the vue component, such as using Sass in the <style> part and Pug in the <template> part; using scoped CSS; you can use the resources referenced in the <style> and <template> Treat as a module dependency
- vue-loader is not a simple source converter. It processes each language block in SFC (Single-file Component) with its own dedicated load chain, and finally composes these blocks into the final module.
- In the process of compiling the module, vue-loader can treat the content of the script as a .js file (if it is <script lang="ts", it will be regarded as a .ts file), in line with the rules of each module of webpack, vue-loader You can parse the code in <template> <script> <style> separately and apply webpack configuration
- For example: suppose we have configured babel-loader for all *.js and processed by vue-loader, these rules will also be copied and applied to the <script> block of Vue SFC.
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。