Home>Article>Web Front-end> Summarize some common front-end interview questions (with answers) to help you consolidate your knowledge!
The main purpose of publishing articles is to consolidate my knowledge and become more proficient. It is all based on my own understanding and the information I searched online. If there is something wrong, I hope you can give me some advice. Below are some common interview questions I have summarized. In order to urge myself, I will continue to update
In the js language, each instance object has a__proto__
attribute, which points to its prototype object, and the constructor of this instance object There is a prototype attributeprototype
, which points to the same object as the __proto__ attribute of the instance object. When the object is looking for the value of an attribute, if it does not have one, it will refer to his ## based on __proto__. #PrototypeSearch on the prototype object. If it does not exist, it will search on the prototype object of the constructor that generated the instance object. If it still does not exist, it will continue to search on the prototype object of Object. If it searches upward, it will be null. , this chain search process is called
Prototype Chain.
prototypeThe prototype object refers back to this constructor through its
constructorattribute, indicating which constructor the prototype object was generated by. The prototype object is an instance object generated by the new keyword. This instance object can point to the prototype object of the constructor that generated the instance object through the
__proto__attribute, realizing a triangular relationship.
1) Prototype chain inheritance
With the help of prototypes, objects can be created based on existing objects, and there is no need to create your own. Define type. Inside the object() function, a temporary constructor is first created, then the passed in object is used as the prototype of the constructor, and finally a new instance of this temporary type is returned. Key code:Star.proyotype = new Person(), Star.proyotype.constructor = StarDisadvantage: Only the methods of the parent class can be inherited
2) Borrowing constructor inheritance
Call the supertype constructor inside the subclass constructor. Constructors can be executed on newly created objects by using theapply()and
call()methods. Key code:
Person.call(this,age,name)Disadvantage: cannot be reused, can only inherit the attributes of the parent class
3) Combined inheritance
Also called pseudo-classical inheritance. It refers to combining the techniques of prototype chaining and borrowing constructors to take advantage of the best of both worlds. Use the prototype chain to inherit prototype properties and methods, and borrow constructors to inherit instance properties. It not only realizes function reuse by defining methods on the prototype, but also ensures that each instance has its own attributes. But there will be a small bug. There are two copies of age and name, and the value of one is undefined, because theapply()and
call()methods will automatically Called once.
4) Parasitic combination inheritance
Inherit properties by borrowing constructors, and inherit methods through the mixed form of the prototype chain. Essentially, you use parasitic inheritance to inherit from the supertype's prototype and then assign the result to the subtype's prototype. It is recognized as a comprehensive method of inheritance. If you want to write it all, it is still very much. I only know a simple one?, the key code:Star.prototype = Object.create(Person.prototype)
5) ES6’s Class class inheritance method
You can use the class keyword together with the extends keyword to achieve inheritance. The class keyword was introduced in ES6 to declare a class, and class (class) can inherit the properties and methods of the parent class throughextends,
superpoints to the prototype object of the parent class, and can be called The attributes and methods of the parent class, and the super keyword must be in the constructor method of the subclass and must appear before this.
Data types are generally divided into two types
typeofDetect existing problems: null or the array is printed as object
instanceof
(Only complex data types can be detected)
The return value is true or false As long as the relevant constructor is on the prototype chain, it is true, otherwise it is false. It can be used to detect whether it is an array
##Object.prototype.toString.call(Required Detected data value)
Why do you need to borrow Object.prototype.toString? Because your toString has been rewritten by your own prototype and you cannot get something like [object Object]
var arr = [2, 3, 4] console.log(arr instanceof Array) console.log(Array.isArray(arr)) console.log(Object.prototype.toString.call(arr))
1. Use lodash shallow copy
clonemethod, let them point to different addresses
2. Use
Object.assignmethod
3. Use es6 Grammar
...Extension operator
1. Use
JSON.parse(JSON.stringify(obj)), Disadvantage: When the object has methods and undefined properties, they will be lost
2. Use
recursion
Stack overflow will appear
let obj = { name: "zs", age: 20, father: [2, 3, 4], }; function deepClone(target) { //这一行如果不用三元判断 如果是数组会有bug会被拷贝成伪数组对象 let tempObj = Array.isArray(target) ? [] : {}; for (let key in target) { if (typeof target[key] === "object") { tempObj[key] = deepClone(target[key]); } else { tempObj[key] = target[key]; } } return tempObj; } let obj1 = deepClone(obj); console.log(obj1);
2.slice will return a new array, which can be used to intercept the array.
3.In addition to deletion, splice can also be replaced and added to the array.
4.splice can pass in 3 parameters, slice Accepts 2 parameters
The
, in ES5 we can use var to declare variables -Use let and const functions- Prevent classic scenarios of variable promotion in for loops
-
Do not pollute global variables
1. The variable declared by the var keyword exists,
The problem of variable promotion;2. The variable declared by var does not exist
Block-level scope
, if so Global variables can be called anywhere;3. If the name of the var declaration variable is repeated, the later declaration will overwrite the previous declaration;
1.
No variable promotion, there is no variable promotion problem when let declares a variable: if the variable is called before let declares the variable, an error will be reported (prompt that the variable cannot be accessed before initialization) ;2.
Block-level scope
, let declares that variables exist in block-level scope (global, function, eval strict mode), which only takes effect in the current code block. If it is outside the current code block The call will report an error (the current variable is not defined);3.
Does not affect the operation of the scope chain4.
Does not allow repeated declaration of variables
, let declaration Variables are not allowed to be declared repeatedly. If the same name is declared repeatedly, an error will be reported (the current identifier has already been declared);
1. Variables declared by const also have the following characteristics:
No variable promotion,block-level scope
,repeated declaration
is not allowed;2.const The declared variables are all
constants
(amounts that are not allowed to change). Once declared, they are not allowed to be modified. If modified, an error will be reported - constant variable assignment3. Generally, in third-party frameworks, Extensive use of const to declare variables can prevent users from modifying variables in the framework;
4. What const actually guarantees is not that the value of the variable cannot be changed, but that the data stored in the memory address pointed to by the variable cannot be changed. For simple types of data (numeric values, strings, Boolean values), the value is stored at the
memory address
pointed to by the variable, so it is equivalent to a constant.
function debounce(func, delay) { let timer = null // 计时器 return function (...args) { clearTimeout(timer) // 清除上一次计时器 timer = setTimeout(() => { // 重新定时 func.apply(this, args) }, delay) } }
节流
function throtte(func, time) { let timer = null // 计时器 return function (...args) { if (timer) return // 无视,直接返回 timer = setTimeout(() => { func.apply(this, args) }, time) } }
这点简单介绍概念,用法后面在详细介绍
1) . 初始态pending
- pending。它的意思是 "待定的,将发生的",相当于是一个初始状态。创建[Promise]对象时,且没有调用resolve或者是reject方法,相当于是初始状态。这个初始状态会随着你调用resolve,或者是reject函数而切换到另一种状态。
2 ). 成功态resolved--
也叫fulfilled
- resolved。表示解决了,就是说这个承诺实现了。 要实现从pending到resolved的转变,需要在 创建Promise对象时,在函数体中调用了resolve方法(即第一个参数)。
3) . 失败态rejected
- rejected。拒绝,失败。表示这个承诺没有做到,失败了。要实现从pending到rejected的转换,只需要在创建Promise对象时,调用reject函数。
// 上口诀 双层for循环 外层长度-1 内层长度-1-i let arr = [4, 3, 1, 7, 8, 10] for (let i = 0; i arr[j + 1]) { let temp = arr[j] arr[j] = arr[j + 1] arr[j + 1] = temp } } } console.log(arr)
MVVM
是三个单词的缩写,model
(数据,一般来自ajax或本地存储)+view
(视图template)+viewmodel(vue实例)
好处
:
降低了耦合性
)
1.分别是创建阶段的beforeCreate
,created
,一般在beforeCreate写loading加载效果,使用户体验更好,一般在created中发送ajax请求获取数据
2.然后是挂载阶段的beforeMount
,mounted
,一般会在mounted中操作DOM元素
3.更新阶段的是beforeUpdate
,updated
,当数据更新时需要做统一的业务处理时,拿到最新的dom,可以使用updated 这个钩子函数
4.最后是销毁阶段的beforeDestroy
,destroyed
,可以在beforeDestroy做一些清理的工作,比如说定时器 和解绑一些addEventListener监听的事件
keep-alive
的两个钩子函数,使用场景是当组件切换时会进行销毁,因此组件中的初始化的4个钩子函数会多次执行,比较浪费资源,此时可以使用keep-alive纪行组件的缓存,可以让组件切换时不被销毁,keep-alive有两个独有的钩子函数,分别是activated
和deactivated
,是组件激活和失活时会执行的两个钩子函数)单向数据流是指父组件向子组件传递数据,子组件通过props
接收,当父组件中的值改变了,子组件中对应的数据也会改变,因为props是只读
的,所以无法直接在子组件中对父组件传递过来的值进行修改,但是如果这个数据是一个引用数据类型,是可以直接在子组件中修改数据中的某个属性的,只要不改变这个数据的内存地址
就可以
vue中普通指令都可以实现数据变了,视图会跟着变,但是有一个特殊的指令叫v-model
,它一般用于表单控件,它可以实现双向数据绑定,所谓的双向数据就是数据变了,视图就会跟着改变,反过来也是
v-model
一般配合input
框使用,实现双向数据绑定的效果,它是v-bind
和v-on
的语法糖,原理是通过v-bind将数据绑定给input框,再通过v-on:input
,在input中的值改变时,通过$event可以获取到事件源对象 再通过target.value
获取到input中更新后的值 将这个值再赋值给绑定的数据即可
在vue的组件使用自定义事件时,$event代表子组件抛出的数据,当这个自定义事件触发一个方法时, 可以不传$event而且可以在方法中进行接收,但是如果写的话就一定要写成$event的形式,这是一个固定写法, 或者这个方法既要传参又要使用事件对象,这个时候$event也是必须要写的 - @click='fn' 在回调函数直接通过参数可以拿到事件对象 - @click='fn($event)' 这个时候@event是固定写法
1.初始化阶段时,先执行父组件的beforeCreate
、created
、beforeMount
三个钩子函数,然后执行子组件的beforeCreate
、created
、beforeMount
、mounted
四个钩子函数,最后执行父组件的mounted钩子函数
2.更新阶段,先执行父组件的beforeUpdate
,然后执行子组件的beforeUpdate
,updated
,最后执行父组件的updated
3.销毁阶段,先执行父组件的beforeDestroy
,然后执行子组件的eforeDestroy
,destroyed
,最后执行父组件的destroyed
v-if
和v-show
都可以控制标签,实现组件的显示与隐藏,不同点是v-show是通过display
的block和none
属性来控制的,当元素隐藏时,页面结构依然存在
v-if是通过将元素创建和销毁来控制显示与隐藏的,当v-if的条件为否时,会直接销毁该元素,当满足时会重新创建出来,有可能会影响页面的回流或重绘
如果该元素需要频繁切换时可以使用v-show,不需要频繁切换时可以使用v-if,提高性能
template
将v-if写在循环的外部,这样当不满足v-if的判断条件时,就不会再执行v-for了,也可以将数据放在计算属性
里面计算过滤出来的数据在交给v-for循环,代替v-if的作用,即可解决。应用场景
v-imgerror
公司项目中有的用户头像可能加载报错,可以给他一张默认图片, onerror this.img=默认图片
v-focus
打开带有搜索的页面的时候,实现自动把光标定位到 input 中
自定义指令的钩子函数
1.bind
属性绑定的时候执行 只会有一次
2.inserted
当前指令所在的元素插入到页面中的时候执行一次
3.update
当前指令所在的组件中的 data 数据有更新就会执行,可以执行多次
// 指令的钩子有三个 bind inserted update // bind inserted 只会执行一次 // update 会反复执行 Vue.directive('focus', { inserted(el) { el.focus() }, }) Vue.directive('red', { bind(el) { el.style.color = 'red' }, }) Vue.directive('check', { update(el) { const reg = /^[a-zA-Z0-9]+$/ if (reg.test(el.value)) { el.style.color = 'green' } else { el.style.color = 'red' } }, })
这块部分理解不是很透彻,大家浅看一下就可以了?
expire
,cache-control
,last-modified
,etag
(In response message)expire
,catch-control
(if there is, the priority is to look atcache-control
), if it is not expired, use That's fine (this piece belongs to strong cache). But if it is found that it has expired, it will start to enter the cache negotiation stage, and send a request to the server toif-modified-since
(the value islast-modifieded
)/if-none-match(etag)
After the request is sent, the server starts to compare to see if the resources on the server are newer than the local ones. If the server resources are still old, a status is returned. The code is 304. When the browser sees that the status is 304, it will continue to use local offline resources. If the server resource has updated resources, the status code is 200, and the server needs to pass a new logo.png to the browser, and the process is repeated.My technology stack is mainly front-end vue, so I still lack knowledge in this area, so I will try my best to explain it clearly. , in fact, I don’t understand it very well. I roughly understand that if you want to fully understand it, you still need a lot of technical reserves. Obviously I am not one, haha?
The observer pattern means that an object is dependent on multiple objects. When the dependent object is updated, all dependent objects will be automatically notified.
The observer pattern is defined A one-to-many dependency relationship between objects. When the state of an object changes, all objects that depend on it will be notified and automatically updated.
Metaphor:
Baby-> Parents, grandparents One-to-many dependency relationship
Baby Cry-> Parents and grandparents rush over to serve. When the status of an object changes, all objects that depend on it will be notified and automatically updated
Mode features: There aretwo subjects
One is the observedDep
The other is the observerwatcher
, in vuev- band
adopts this model concept. The disadvantage is that the coupling is too high
Publish-subscribe model In fact, it is a one-to-many dependency relationship between objects. When the state of an object changes, all objects that depend on it will be notified of the state change.
In the current publish-subscribe model, the message sender called the publisher does not send messages directly to the subscribers, which means that the publisher and the subscriber do not know each other’s exist. There is a third component between the publisher and the subscriber, called the dispatch center or event bus, which maintains the connection between the publisher and the subscriber, filters all incoming messages from the publisher and responds accordingly Distribute them to subscribers
Mode features: There arethree subjects
Publisher dispatch center subscribers, reflected in vueeventBus
This model concept can achieve decoupling
The number of subjects is different. The observer mode has two subjects, namely the observedDep
and the observerwatcher
. The publish and subscribe model has three subjects, namely the publisher dispatching center (event channel) and the subscriber
Compared with the observer mode, the publish-subscribe mode has one more event channel. The event channel serves as a dispatch center to manage the subscription and publishing of events, completely isolating the dependence between the subscriber and the publisher. Subscribers and publishers are decoupled (not aware of each other's existence)
(Learning video sharing:Web front-end introduction,jQuery video tutorial)
The above is the detailed content of Summarize some common front-end interview questions (with answers) to help you consolidate your knowledge!. For more information, please follow other related articles on the PHP Chinese website!