1. Variable type and calculation

  / / value types
  let a = 100
  let b = a;
  a = 200;
  console.log(a); / / 200
  console.log(b); / / 100
  
  // Reference type
  let a = { age: 20};
  let b = a;
  b.age = 21;
  console.log(a.age); / / 21
Copy the code

Value types do not affect each other

let a; Failure to use const will cause an errorCopy the code

The difference between deep copy and shallow copy

Shallow copy and deep copy

The difference between deep copy and shallow copy

The way to distinguish between A deep copy and A shallow copy, to put it simply, is to assume that B copies A, and when you modify A, see if B changes. If B also changes, it’s A shallow copy. If B doesn’t change, it’s A deep copy.

Shallow copy

 var obj = { a: 1, arr: [2, 3] };
  var shallowObj = Object.assign({}, obj);
  shallowObj.arr[1] = 0;
  shallowObj.a = 'yanbo';
  console.log(obj, 'obj');
  console.log(shallowObj, 'shallowObj');
Copy the code

Deep copy

Deep copy / / / / get type function getType (obj) {var toString = Object. The prototype. ToString. var map = { '[object Boolean]': 'boolean', '[object Number]': 'number', '[object String]': 'string', '[object Null]': 'null', '[object Undefined]': 'undefined', '[object Array]': 'array', '[object Function]': 'function', '[object RegExp]': 'regExp', '[object Date]': 'date', '[object Object]': 'object'} if (obj instanceof Element) {// toString returns constructor 'Element' for different tags; } return map[toString.call(obj)]; } function deepClone(data) { var type = getType(data) var obj; if (type === 'array') { obj = [] for (var i = 0; i < data.length; i++) { obj.push(deepClone(data[i])) } } else if (type === 'object') { obj = {} for (var key in data) { obj[key] = deepClone(data[key]); } } else { obj = data; } return obj; } var oldObj = { a: 1, b: 2 } const newObj = deepClone(oldObj); const newObj1 = newObj.c = 4; console.log(oldObj, newObj) let oldData = [1, 2, 3, 4, 4]; const newData = deepClone(oldData); const newData1 = newData.push({ a: 4, b: 7 }); console.log(newData, '--->newData', oldData, '---->oldData');Copy the code

The second kind of deep copy

Json.parse (json.stringify (obj)) is usually used for deep copy. The process is to serialize the JS object (JSON string) using json.stringify, and then deserialize (restore) the JS object using json.parse. Serialization is used for storage (the object itself only stores an address map, if the power is turned off, the object will no longer exist, Therefore, the Content of the object needs to be converted into a string and saved on disk (for example, if the requested content-type is Application/X-www-form-urlencoded, Then the front end needs to use qs.stringify(data) to serialize the parameters and pass them to the back end, otherwise the back end cannot receive them; Ps: the content-type for application/json; Charset =UTF-8 or multipart/form-data is not required).

If obj contains a time object, then the result of json. stringify followed by json. parse will be a string of time. Rather than a time object;

  var a = {
    name: 'aaa',
    date: [new Date(1536627600000), new Date(1540047600000)]
  }
  let b;
  b = JSON.parse(JSON.stringify(a))
  console.log(a);
  console.log(b);
Copy the code

If obj contains RegExp and Error objects, then the serialized result will be null;

  const test = {
    name: 'a',
    date: new RegExp('\\w+'),
  };
  // debugger
  const copyed = JSON.parse(JSON.stringify(test));
  test.name = 'test'
  console.log(test);
  console.log(copyed);
  console.error('ddd', test, copyed)
Copy the code

3, if obj contains function, undefined, then the serialization result will lose the function or undefined;

  const test = {
    name: 'aaa',
    date: function hello() {
      console.log('ffff');
    }
  }
  const copy = JSON.parse(JSON.stringify(test));
  test.name = 'js';
  console.log(test)
  console.log(copy);
Copy the code

If NaN, Infinity and -infinity are in obj, the serialized result will be null

String concatenation

Focus on

Class and inheritance

Class Student {constructor(name, constructor); Number) {this.name = name this.number = number // this.gender = 'male'} sayHi() {console.log(' name ${this.name}, ${this.number} ') // console.log(// 'name' + this.name + ', '+ this.number //)} // study() {// const xialuo = new Student(' Charlotte ', 100) console.log(xialuo.name) console.log(xialuo.number) const madongmei = new Student(' madongmei ', 101) console.log(madongmei.name) console.log(madongmei.number) madongmei.sayHi()Copy the code
Class People {constructor(name) {this.name = name} eat() {console.log(' ${this.name} eat something ')}} // Class Student extends People {constructor(name, constructor) Number) {super(name) this.number = number} sayHi() {console.log(' name ${this.name} student ID ${this.number} ')}} // Subclass class Teacher extends People { constructor(name, Major) {super(name) this.major = major} teach() {console.log(' ${this.name} professor ${this.major} ')}} const xialuo = new Student(' Charlotte ', Log (xialuo.name) console.log(xialuo.number) xialuo.sayhi () xialuo.eat() const wanglaoshi = new Teacher(' Wang Teacher ', 'Chinese ') console.log(wanglaoshi.name) console.log(wanglaoshi.major) wanglaoshi.teach() Wanglaoshi.eat ()Copy the code

Instanceof determines the reference type

Prototype chain

Scope and closure

This is determined when the function is executed, not when the function is defined

Asynchronous and single threaded

What is an event object? Event agent, event delegate, event capture, event bubble

What is an event?

An event object is an object that is automatically created by the system when a registered event is triggered

Event object note:

  • In advanced versions of the browser, the event object is automatically passed to the return function
  • In lower-level versions of the browser, event objects are not automatically passed to callbacks
  • In lower-level browsers, you need to get the event object through window.event

Register event

var oBtn=getElementByoId("btn");
oBtn.onclick=function(event){ // The event object is passed
 event = event || window.event;// Compatibility
 console.log(event);  //Object 
}
Copy the code

Prevent default behavior (link jump) return false Enterprise development recommendation

The preventDefault method only supports advanced browsers

Event.preventdefault () event.returnValue = false // Browsers below IE9Copy the code
let oA = document.querySelector("a"); OA. The onclick = function (event) {/ / compatibility of writing event = event | | window. The event; alert("666"); // Prevent default behavior return false; // Enterprise dev recommendation // Note: preventDefault only supports advanced browsers // event.preventdefault (); // event.returnValue = false; // For browsers below IE9}Copy the code

The three ways to add events are through the onXXX method

[Note :]

Since you are assigning a value to an attribute, the later assignment overrides the first assignment

Added via the addEventListener method

Note:

  • 1. You do not need to add on to the event name
  • 2. The new one does not overwrite the first one
  • 3. Only Internet Explorer 9 is supported

Add a note via the attachEvent method:

  • 1. The event name must be on
  • 2. The new one does not overwrite the first one
  • 3. Only browsers of earlier versions are supported
var oBtn = document.getElementById("btn"); */ obtn. onclick = function () {alert("666"); / / obtn. onclick = function () {alert("666"); } oBtn.onclick = function () { alert("777"); */ obtn.addeventListener ("click", function () {alert("666"); }); oBtn.addEventListener("click", function () { alert("777"); // will not cover 666, show in sequence}); */ obtn.attachevent ("onclick", function () {alert("666"); }); oBtn.attachEvent("onclick", function () { alert("777"); }); addEvent(oBtn, "click", function () { alert("666"); }) addEvent(oBtn, "click", function () { alert("777"); Function addEvent(ele, name, fn) {if(ele.attachevent){ele.attachevent ("on"+name, fn); }else{ ele.addEventListener(name, fn); }}Copy the code

Only two of the three phases will be executed at the same time either capture and current, or current and bubble

Why should it be either capture and current or current and bubble only? This is the historical problem of JS handling events in the early stage of the major browser manufacturers to occupy the market, as well as the understanding of the event is different subsequent W3C in order to be compatible, the two ways are included in the standard

How do you set whether an event is captured or bubbled? Through the addEventListener method, this method takes three arguments

  • First argument: the name of the event
  • The second argument: the callback function
  • Third argument: false bubble/true capture

{note 】

  • The onXxx attribute does not take any arguments, so the default is bubble
  • The attachEvent method can only take two arguments, so the default is bubble
<div id="app"> <div id="app"> <div id="app"> -- Note: By default, event callbacks can be executed repeatedly, as long as the event is fired once. Once the modifier - > < button @ click. Once = "myFn (' knocking, 18, $event)" > point I < / button > <! <a href="https://www.baidu.com" @click. Prevent ="myFn"> </a> <! If you want the callback function to execute only when the current element fires an event, you can use the. Self modifier event bubble -- event capture, Use @click.capture --> <div class="a" @click.capture="myFn1"> <div class="b"@click.capture="myFn2"> <div class="b"@click.capture="myFn2" class="c"@click.capture="myFn3"></div> </div> </div> </div>Copy the code

The V-on directive is used to listen for events specifically bound to an element

2. Command format V-ON: event name = "callback function name" @ event name = "callback function name" 3. Note: 3.1. After the v-on binding event is triggered, it will find the corresponding callback function 3.2 in the Methods of Vue instance object. Write on when you do not need to specify the event name. 3.3. You must assign the name of the callback function 3.4. Stop - To call event.stopPropagation(). To call event.stopPropagation(). To call event.stopPropagation() .prevent - Call event.preventdefault (). .capture - Use capture mode to add event listeners. .self - The callback is fired only if the event is fired from the element itself to which the listener is bound. . {keyCode | keyAlias} - only events from the specific trigger callback key trigger. Native - Listens for native events on the component root element. .once - Triggers only one callback. .left - (2.2.0) Is triggered only when the left mouse button is clicked. .right - (2.2.0) is triggered only when the right mouse button is clicked. .middle - (2.2.0) Is triggered only when the middle mouse button is clicked. . Passive - (2.3.0) Add a listener in {passive: true} mode 5. The common modifier.once - fires a callback only once. .prevent - Call event.preventdefault (). .self - The callback is fired only if the event is fired from the element itself to which the listener is bound. .stop - Call event.stopPropagation(). @click= "Fn" @click= "Fn ()" @click= "Fn ()" You can pass @click= "Fn ("dxy",18)" to the bound callback function 3. If you want to use data in the bound function, you must add thisCopy the code

Event loop mechanism

 setTimeout(function () {
    console.log(2);
  }, 0);

  new Promise(function (resolve){ // Instantaneous execution
    console.log(3);
    resolve();
    console.log(4);
  }).then(function () {
    console.log(5);
  })

  console.log(8);
Copy the code

Implementation process

The difference is that the timing of the click is not the same as the user click to trigger

Promise

Promise loads an image case

<script>
  function loadImg (src) {
    const p = new Promise((resolve, reject) = > {
      const img = document.createElement('img');
      img.onload = () = > {
        resolve(img)
      }
      img.onerror = () = > {
        const err = new Error('Failed to load the image${src}`);
        reject(err);
      }
      img.src = src;
    })
    return p;
  }

const url = 'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fcdn.duitang.com%2Fuploads%2Fitem%2F201410%2F04%2F20141004172507_J 8 mty.jpeg&refer=http%3a%2f%2fcdn.duitang.com & app = 2002 & size = f9999, 10000 & q = a80 & n = 0 & g = 0 n & FMT = jpeg? = 1628686602 & t = 6 b687776 the SEC 4738eb1c2a763b71aa07523d';

  const p = loadImg(url);

  p.then(img= > {
    console.log(img.width);
    return img;
  }).then(img= > {
    console.log(img.height);
  }).catch(ex= > {
    console.log(ex);
  })

</script>
Copy the code

Function loadImg(SRC) {const p = new Promise( (resolve, reject) => { const img = document.createElement('img') img.onload = () => { resolve(img) } img.onerror = () => { const Err = new Error(' image loading failed ${SRC} ') reject(err)} img.src = SRC}) return p} const URL = 'https://img.mukewang.com/5a9fc8070001a82402060220-140-140.jpg' loadImg(url).then(img => { console.log(img.width) return  img }).then(img => { console.log(img.height) }).catch(ex => console.error(ex))Copy the code

Three states

Pending resolved states

(Drawing shows the transformation relationship and the irreversibility of the transformation)

// When defined, the state defaults to pending
const p1 = new Promise((resolve, reject) = >{})// The resolved state changes to resolved after the resolve() command is executed
const p2 = new Promise((resolve, reject) = > {
    setTimeout(() = > {
        resolve()
    })
})

// After executing reject(), the state becomes rejected
const p3 = new Promise((resolve, reject) = > {
    setTimeout(() = > {
        reject()
    })
})

Copy the code
// Return to the resolved state
Promise.resolve(100)
// Return the rejected state
Promise.reject('some error')
Copy the code

State and then catch

A state change triggers a then catch — these are easy to understand, so I won’t show them in the code

  • Pending does not trigger any THEN catch callbacks
  • Changing to the Resolved state triggers subsequent THEN callbacks
  • A state change to Rejected triggers a subsequent catch callback

Then the catch will continue to return the Promise, and the state may change!!

// Then () Return the promise in the resolved state normally
Promise.resolve().then(() = > {
    return 100
})

// Then () throws an error and returns a promise in the rejected state
Promise.resolve().then(() = > {
    throw new Error('err')})// Catch () does not throw an error and returns a promise in the resolved state
Promise.reject().catch(() = > {
    console.error('catch some error')})// Catch () throws an error and returns a promise in the rejected state
Promise.reject().catch(() = > {
    console.error('catch some error')
    throw new Error('err')})Copy the code

Look at a comprehensive example of the interview questions

/ / 1
Promise.resolve().then(() = > {
    console.log(1) / / 1
}).catch(() = > {
    console.log(2)
}).then(() = > {
    console.log(3) / / 3
}) // resolved

/ / the second question
Promise.resolve().then(() = > { // Return the promise in the rejected state
    console.log(1) / / 1
    throw new Error('erro1')
}).catch(() = > { Return the promise in the resolved state
    console.log(2) / / 2
}).then(() = > {
    console.log(3) / / 3
})// Return the promise of resolve

/ / the third topic
Promise.resolve().then(() = > { // Return the promise in the rejected state
    console.log(1)
    throw new Error('erro1')
}).catch(() = > { Return the promise in the resolved state
    console.log(2)
}).catch(() = > {
    console.log(3) // Will not be executed
})
Copy the code

For of asynchronous loop 1 then 4 then 9

Chapter 12 Ajax

Core code

 const xhr = new XMLHttpRequest();
  xhr.open('get'.'/api'.false); // True means asynchronous, false means synchronous
  xhr.onreadystatechange = function () {
    // This function is executed asynchronously, refer to the previous js basic asynchronous module
    if (xhr.readyState === 4) {
      if (xhr.status === 200) { alert(xhr.responseText); }}}Copy the code

const xhr = new XMLHttpRequest();
  xhr.open('POST'.'/data.json'.true); // True indicates asynchrony
  xhr.onreadystatechange = function () {
    // This function is executed asynchronously, refer to the previous js basic asynchronous module
    if (xhr.readyState === 4) {
      if (xhr.status === 200) {
        alert(xhr.responseText);
      } else {
        console.log('Other cases'); }}}const postData = {
    userName: 'zhangsan'.password: 'xxx'
  }
  xhr.send(JSON.stringify(postData));
Copy the code

Cross domain

The same-origin policy

When making an Ajax request, the browser requires that the current page and server must be the same source (security).

Cognate: The protocol, domain name, and port must be the same

/** * Write easy Ajax *@param Url Url splicing *@param Method Request method *@param SuccessFn callback function */
  function ajax (url, method, successFn) {
    const xhr = new XMLHttpRequest();
    xhr.open(method, url, true)
    xhr.onreadystatechange = function () {
      if (xhr.readyState === 4) {
        if (xhr.status === 200) {
          successFn(xhr.responseText)
        }
      }
    }
    xhr.send(null);
  }
Copy the code
@param url * @param method */ function ajax(url, method) {const p = new promise ((resolve,)) reject) => { const xhr = new XMLHttpRequest(); xhr.open(method, url, true) xhr.onreadystatechange = function () { if (xhr.readyState === 4) { if (xhr.status === 200) { resolve( JSON.parse(xhr.responseText) ) } else if (xhr.status === 404) { reject(new Error('404 not found')); } } } xhr.send(null); }) return p; } const url = '/data.json'; ajax(url, 'get').then(res => { console.log(res) }).catch(err => { console.log(err); })Copy the code

Chapter 14 HTTP interview questions

methods http

HTTP cache

What is cache?

We’re reacquiring things that we don’t have to reacquire. We don’t have to

Why is caching needed?

Make pages load faster

Mandatory cache

Cache-Control

Value of cache-control max-age: indicates the maximum time for the cache to expire. No-cache: indicates that the local cache is not used and the server processes the cache. No-store: indicates that the local cache is not used and the server cache is not used

Git Commands

Git checkout -b XXX New branch Git checkout branch name Switch branch Git merge XXX Merge branches git branch -a Find all branches git branch Check the current branch git checkout . A record of all the changes you madeCopy the code