Interview Answer 1

vuex property

  1. state: declaration defines data
  2. getters: storing data dependency, similar to the calculation of computed attribute
  3. mutation: synchronous data submissions in the state
  4. actions: modify data in asynchronous
  5. modules: Let each module has its own state, getters, mutation, actions

Vue principle of two-way binding

Vue two-way binding principle is to use the Object.defineProperty () this method redefines the object to get attribute values ​​(get) and set the property values ​​(set) operation to achieve.

What vue family bucket (❎)

  1. Vue-cli project build tools
  2. vue-router route
  3. vuex state management
  4. axios http request tool
  5. webpack

vue some common commands

  1. v-for now with: key Use
  2. Whether the v-if render this tag
  3. v-bind shorthand:
  4. v-show display control none / block
  5. v-else with v-if used
  6. v-on shorthand @

Why vue of data is returned by the function

Because a component can be shared, but their data is private, so each component should return a new object and returns a unique object, and other components that do not share an object

The combined method array

  1. concat
var a = [1,2,3]
var b = [4,5,6]
var c = a.concat(b)  //c = [1,2,3,4,5,6]
  1. apply
var a = [1,2,3]
var b = [4,5,6]
var c = a.push.apply(a,b)
  1. Deduplication Array merge
let arr1 = [1,2,3]
let arr2 = [2,3,4]
let arr = arr1.concat(arr2) //合并数组
let arrNew = new Set(arr)  //通过set集合去重
Array.from(arrNew)  //将set集合转化为数组

Vertically centered manner (❎)

  1. absolute + transform: + absolute positioning conversion
.parent {
    position: relative;
}
.child {
    position: absolute;
    left: 50%;
    rigth: 50%;
    transfrom: translate(-50%,-50%)
}
  1. flex + justify-content + align-items
.parent {
    display: flex;
    justify-content: center; //水平居中
    align-items: center;   //垂直居中
}

Interview the next day

Difference call, apply, bind to, implement the following methods (❎)

  1. call and apply all point to this change in order to solve the. Action are the same, but different parameter passing mode. In addition to the first parameter, call a list of acceptable parameters, apply only one parameter array accepts

call the realization of ideas

//call的实现思路
Function.prototype.myCall = function (context){
  if (typeof this !== 'function') {
     throw new TypeError('Error')
  }
  var context = context || window
  //给context添加一个属性
  context.fn = this
  //通过参数伪数组将context后面的参数取出来
  var args = [...arguments].slice(1)
  var result = context.fn(...args)
  //删除 fn
  delete context.fn
  return result
}

apply the realization of ideas

//apply的实现思路
Function.prototype.myApply = function (context) {
    if (typeof this !== 'function') {
     throw new TypeError('Error')
  }
    var context = context || window
    //为context添加一个属性
    context.fn = this
    var result 
    //判断是否存在第二个参数
    //如果存在就将第二个参数也展开
    if(arguments[1]) {
        result = context.fn(...arguments[1])
    } else {
        result = context.fn()
    }
    delete context.fn
    return result
}

The realization of ideas bind: bind returns a function, a function is invoked, there are two ways, one is a direct call, one is the new way through

Function.prototype.myBind = function (context) {
    if (typeof this !== 'function') {
        throw new TypeError('Error')
    }
    const _this = this 
    const args = [...arguments].slice(1)
    //返回一个函数
    return function F () {
        if (this instanceof F) {
            return new _this(...args, ...arguments)
        }
        return _this.apply(context,args.concat(...arguments))
    }
}

vue Why use axios

vue is a virtual DOM operations, JQuery.ajax and DOM operations are required, the official is not recommended, but axios itself can solve the problem of callback hell

and the difference between session and cookie window.localstore of (❎)

loaclStorage lifecycle is permanent storage of data is generally 5MB; sessionStorage valid only in the current session, or close the page after clearing the browser, stored data size is generally 5MB; cookie with high scalability and availability, data storage size about 4k, there is limit to the number, generally not more than 20. localStorage, sessionStorage, Cookie thing in common: both are stored in the browser, and homologous.

Process for new operations (❎)

Procedure 1. freshmen became an object link to the prototype 2. 3. bind this 4. returns a new object fact, we can achieve a new own: The call will take place in the course of four things new

function createNew() {
  let obj  = {}
  let Sunday  = [].shift.call(arguments)
  obj.__proto__ = Sunday.prototype
  let result = Sunday.apply(obj,arguments)
  return result instanceof Object ? result : obj
}

vue-router principle (❎)

vue-router routing routing offers two modes: hash mode and a history mode. - hash mode: ue-router default hash mode - use the URL to simulate a complete hash of the URL, so when the URL changes, the page will not reload. - history mode: If you do not want to hash ugly, we can use history routing mode, this model take advantage of history.pushState API URL to complete the jump without having to reload the page

Communication component vue

Generally divided into three components of the communication: 1. The components of the communication Sons - parent component subassembly to pass through The props data, transmitting data transfer subassembly $ EMIT data, the data can not be modified subassembly parent element, parent-child communication is typical of a single component the data stream. 2. Brothers communication components - for this situation by looking subassemblies parent components to achieve, that is, this $ parent $ children, in $ children can be queried by the assembly name to the component instance need, and then communicate... 3. Pending components communicate across multi-level

Interview Day

Cross-domain

  1. JSONP
//jsonp的原理很简单,就是利用 <script> 标签没有跨域的限制的漏洞。当需要通讯时,通过 <script> 标签指向一个需要访问的地址,并提供一个回调函数来接收数据。
//JSONP使用简单并且兼容性不错,但是只限于get请求
<script src="http://sunday/api?param8=a&param2=b&callback=jsonp"></script>
<script>
    function jsonp(data) {
        console.log(data)
    }
</script>
  1. HEARTS
cors需要浏览器和后端同时支持。IE 8 和 9 需要通过XDonmainRequest来实现。
 浏览器会自动进行 CORS 通信,实现 CORS 通信的关键是后端,只要后端实现了 CORS ,就实现了跨域。
 服务端设置 Access-C动态容量—Allow-Origin 就可以开启CORS。此属性表示哪些域名可以访问资源。
  1. document.domain
这种方式只能用于主域名相同的情况下,例如sunday.test.com 和 zhaojiujiu.test.com 适用于该方式。
只需要给页面添加 document.domain = 'test.com'表示主域名都相同就可以实现跨域
  1. postMessage
// 发送消息端
window.parent.postMessage('message','http://sunday.com')
//接收消息端
var zhaojiujiu = new MessageChannel()
zhaojiujiu.addEventListener('message',event => {
    var origin = even.origin || event.originalEvent.origin
    if(origin === 'http://sunday.com') {
        console.log('验证通过')
    }
})

Expansion and stabilization functions

First, let's be clear about the definition of the function of the throttle and image stabilization

  • Throttle function: only perform a task within a specified time interval
  • Anti-shake function: if the task frequently triggered only time task trigger interval exceeds the specified interval of time, the task will be performed

Throttling function (Throttle)

The most vivid example is when we scroll the page when scrolling in the end determine whether the department, without considering the throttle function and performance of the code, that is, by listening == window.scorll == events

$(window).on('scroll',function () {
  //判断滚动条是否滚动到页面的底部
  let pagHeight = $('body').height(),
      scroolTop = $(window).scrollTop(),
      winHeight = $(window).height(),
      thresold = pageHeight - scorllTop - winHeight;
  if(thresold > -100 && thresold <= 20) {
    console.log('bottom');
  }
});
//这种情况会非常消耗性能的,在滚动时,浏览器会时刻的监听是否满足滚动的条件,但是在实际的开发中我们是每隔一段时间去执行一次,所以就出现了函数节流的概念
下面试解决函数节流的解决方案:
function throttle(fn) {
  let tag = true;
  return function() {
    if (!tag) return;
    tag = false;
    setTimeout(() => {
      fn.apply(this,arguments);
      tag = true;
    },500)
  }
}

Function Image Stabilization (debounce)

This situation is very common, we do a search function that, when the input data input, each input data will be triggered once requested, when we have finished searching for content, the request will happen a few times, not only the user experience well, even the pressure on the server also increases. Most of our solution is to introduce an anti-shake function (debounce)

//函数防抖的原理
function debounce (fn) {
  let tag = null;
  return function () {
    clearTimeout(tag);
    tag = setTimeout(() => {
      fn.apply(this, arguments);
    },500);
  };
}

In fact, the purpose and function of the throttle anti-shake function, that is, save computer resources.

Closure

-

  • Defined closure:
    the closure is a function of internal variables can be read by other functions, it may be in the closure js understood as a "function of functions"
  • Use closures:
    1. read inside the function variable
    2. Let the variables remain in memory, extend the life cycle of variables
  • Closure conditions:
    1. The functions and subfunctions outer layer 
    2. The outer layer has a function of local variables
    3. Functions can control a function of the local variable layer
    4. Functions associated with the external function
function A() {
  let a = 1
  window.B = function () {
      console.log(a)
  }
}
A()
B() // 1
  • Closed raison d'etre package:
// 使用闭包的方式解决var定义函数问题
for (var i = 0;i<=3;i++){
  (function(j){
    setTimeout(function timer() {
      console.log(j)
    },j*1000)
  })(i)
}

Interview Day

Class inheritance and prototype inheritance

Prototypal inheritance

  • How prototypal inheritance?
    Change the first prototype of a subclass of a prototype point to New parent () object.
子类.prototype = new 父类()

Prototype subclass give a set point subclass constructor

子类.prototype.constructor = 子类
  • Code
// 人类 → 父类
 function Person() {
   this.name = '名字';
   this.age = 10;
   this.gender = '男';
 }
 Person.prototype.sayHi = function () { console.log('你好'); };
 Person.prototype.eat = function () { console.log('我会吃。。。'); };
 Person.prototype.play = function () { console.log('我会玩'); };


 // 学生类 → 子类
 function Student() {
   this.stuId = 1000;
 }
 // 子类的原型prototyp指向父类的一个实例对象
 Student.prototype = new Person();
 // 添加一个constructor成员
 Student.prototype.constructor = Student;

 // 如何实现原型继承:
 // 给子类的原型prototype重新赋值为父类的一个实例对象。
 // 利用了原型链上属性或方法的查找规则。


 // 创建一个学生对象
 var stu1 = new Student();
 console.log(stu1.constructor)

class inheritance

  • You can use class in es6 to inheritance, and is simple to implement
class Parent {
  constructor(value) {
    this.val = value
  }
  getValue() {
    console.log(this.val)
  }
}
class Child extends Parent {
  constructor(value) {
    super(value)
    this.val = value
  }
}
let child = new Child(1)
child.getValue() // 1
child instanceof Parent // true
  • The core class inheritance is the use of which extends show inherited from the parent class, and you must call the super constructor in the subclass, because the code can be viewed as Parent.call (this, value)

Guess you like

Origin www.cnblogs.com/teahouse/p/11313847.html