1. What are the methods and usage scenarios for JS to access internal data variables?

There are two main ways to read and set object properties:

(.). Method: obj. Attr ([]) method: obj[attr]

Grammar is the way we usually use it.

[] is usually used in the following scenarios:

  • The attribute name contains special characters such as – space
  • Variable name indeterminate ([] can be a variable, or a string)

Usage:

let p={}
  let address='address'
  p.name='name'
  p['age'] =12
  p[address]='quiet'
  console.log(p)
Copy the code

2. What are the four ways that Javascript functions can be called?

  • Call the function directly (through the window)
  • Call by object
  • New call (calling a function using a constructor)
  • Call through bind/call/apply

3. Implementation principle of the new operator

To understand how the new operator works, you need to understand what new does. As we all know, we use the new operator when we instantiate our constructors as objects.

To really master and write a new, you need to know about prototypes and prototype chains and the this binding.

In fact, the internal process of New is very simple, which is basically the following steps:

  1. Create a new object, obj
  2. Points the implicit stereotype of an object to the stereotype object of the constructor
  3. Call the constructor with apply (change this to obj)
  4. Return obj, if the constructor has a value, reference object if the value is a reference type, and obj if it is primitive

Writing:

  function MyNew() {
    // Get the list of parameters, get the constructor and its parameters
    let [ArgFun, ...arg] = [...arguments]
    // Define an empty object
    let obj = {};
    // Prototype pointing
    obj.__proto__ = ArgFun.prototype;
    // Set this to point
    let tartgetObj = ArgFun.apply(obj, arg)
    // Call the constructor with apply (change this to obj)
    return tartgetObj instanceof Object= =true ? tartgetObj : obj
  }
Copy the code

Use:

  function Person(name, age) {
    this.name = name;
    this.age = age;
    console.log('execution')
    return '12'
  }

  let zhangsan = MyNew(Person, 'Joe'.12)
  console.log(zhangsan)

Copy the code

4. What native methods do arrays have

  1. Pop () and push() tail operations, delete and add
  2. Shift () and unshift() headers, delete and add
  3. Sort (), a function that takes two arguments and returns an array by subtracting two arguments
  4. Reserve () reverses an array, which also returns an array, changing it
  5. Concat (), concatenates two arrays, returns the concatenated array without changing the original array
  6. Slice (), which takes a portion of an array and returns it, without affecting the original array
  7. Splice (), which can delete, replace, or insert one or more elements of an array, return the array, and alter the original array
  8. The filter() function returns the filtered array without changing the original array
  9. The map() function iterates through the array without changing the original array
  10. Reduce (), a summary, can operate on each array element. The parameters are a function and a default value. The function has two parameters, respectively representing the result of the last calculation and the current value.

5. What are DOM and BOM

Answer this question by including ECMAScript as well.

JavaScript is made up of three parts: ECMAScript, DOM, and BOM. Their functions and tasks are also different:

ECMAScript: Specifies language basics such as syntax, keywords, operators, etc. It specifies language standards such as ES5, ES6, etc

DOM: Document object model that provides methods and interfaces for accessing and manipulating web page content. DOM maps the entire page into a structure of multi-level nodes, each of which is treated as an object, resulting in a DOM tree. If we want to get the object of a node, we just need to get the object layer by layer and then operate it.

BOM: Browser object model that provides methods and interfaces to and from the browser. At the heart of the BOM is the Window object. Windows also provides apis for manipulating the browser, such as the History property, navigator, and Location objects.

Note: Window has a dual identity. It is not only an interface for JS to operate the browser window, but also a global object, which can operate any variable object in the web page

6. The understanding of class array (pseudo-array), how to convert to array

Class array is a pseudo-array, is a kind of array-like object, has the length attribute and a number of index attributes of the object, but can not call the array method

Common array-like objects are arguments and the result returned by DOM methods.

Common ways to convert an array of classes to an array are as follows:

1. Call the array’s slice method via call:

Array.prototype.slice.call(arrayLike);
Copy the code

2. Call the array’s splice method via call:

Array.prototype.splice.call(arrayLike, 0);
Copy the code

3. Call concat methods such as arrays through call

Array.prototype.splice.call(arrayLike, 0)
Copy the code

4. Use the array. from method to convert

Array.from(arrayLike);
Copy the code

5. You can also use the ES6 extension operator

7. Why tail calls?

A first call is simply a call to another function at the end of its execution. We know that function execution is stack based, so the last step of our current function is off the stack, and then we call another function. The advantage of this is that we don’t have to keep the stack of the current function, thus saving memory. This is called tail-call optimization

8.for… In and for… The difference of

  1. For in gets the key name of the object, and for of gets the key of the object
  2. For in traverses the prototype chain of an object and is not recommended for poor performance, while for of traverses only the current object and does not traverse the prototype chain
  3. For in returns all enumerable properties of the array, and for of returns the values of the array line markers.

Summary: For in is mainly used to iterate over objects, not groups of numbers. For of loops can iterate over objects, arrays, array-like objects, etc.

9. Ajax understanding to implement an Ajax request

This is the asynchronous communication of JavaScript, the technique of requesting data asynchronously, getting json data from the server, and updating it to the entire page without refreshing the entire page. This is the biggest advantage of Ajax.

At the heart of Ajax is the XmlHttpRequest object, which JavaScript can use to make requests and process responses without blocking the user.

** HOW it works: ** I think of Ajax as an intermediate layer between the browser and the server, where the client sends a request, the request goes to the XHR object, the XHR sends the request to the server, the server does the business, the server sends the response data to XHR, and JavaScript writes the page.

Steps to create an Ajax request:

  1. Create an XmlHttpRequest object
  2. Create an Http request (you can set the request mode, address, and asynchrony)
  3. Add information and listener functions (such as adding request headers and listening for XHR status)
  4. Send the request (parameters can be passed when post)

We use the following callback to encapsulate a network request function:

  function getData(url, hander) {
    let xhr = new XMLHttpRequest();
    xhr.open('GET', url, true);
    xhr.onreadystatechange = function () {
      if (this.readyState ! = =4) return
      if (this.status == 200) {
        hander(this.response)
      } else {
        console.error(this.statusText)
      }
    }
    xhr.onerror = function () {
      console.log(this.statusText)
    }
    xhr.setRequestHeader("Accept"."application/json")
    xhr.send();
  }
Copy the code

Usage:

	getData('http://httpbin.org/get'.(data) = > {
    console.log(data)
  })
Copy the code

You can also use the promise wrapper:

function UseP(url) {
    return new Promise((resolve, reject) = > {
      let xhr = new XMLHttpRequest();
      xhr.open('GET', url, true);
      xhr.onreadystatechange = function () {
        if (this.readyState ! =4) return
        if (this.status == 200) {
          resolve(this.response)
        } else {
          reject(this.statusText)
        }
      }
      xhr.onerror = function () {
        reject(this.statusText)
      }
      xhr.responseType = 'json'
      xhr.setRequestHeader('Accept'.'application/json')
      xhr.send()
    })
  }
Copy the code

Use:

 UseP('http://httpbin.org/get').then((res) = > {
    console.log(res)
  }).catch((err) = > {
    console.log(err)
  })
Copy the code

10. Differences between Ajax, Axios, and FETCH

Ajax:

A technique for updating parts of a web page without having to reload them. A small amount of data is exchanged with the server through the background. Ajax enables asynchronous updating of web pages. Traditional web pages need to reload the entire page if they need to update the content.

Ajax has the following disadvantages:

  1. Itself is targeted at MVC programming, not in line with the tide of front-end MVVM
  2. Developed based on native XHR, the architecture of XHR itself is unclear
  3. Does not conform to the principle of separation of concerns
  4. Configuration and invocation are messy, and the event-based asynchronous model is unfriendly

Axios:

The HTTP client for the browser and NodeJS is essentially a wrapper around the native XHR, but it’s an implementation version of Promise. There are the following special provisions:

  1. Initiates an XMLHttpRequest request from the browser
  2. The Node sends an HTTP request
  3. Supporting Promise API
  4. Client support prevents CSRF
  5. Provides some interfaces for concurrent requests
  6. Intercept requests and responses
  7. Transform request and response data
  8. Cancel the request
  9. Automatically convert to JSON format

PS: To prevent CSRF: it is to make every request of you carry a key obtained from the cookie. According to the same origin policy of the browser, the fake website cannot get the key obtained from your cookie. In this way, the background can easily identify whether the request is a misleading input of the user on the fake website, so as to adopt the correct policy.

Fetch:

Alternatives to Ajax. Design based on Promise. Fetch’s code structure is much simpler than Ajax, and the parameters are a bit like jQuery Ajax. However, keep in mind that FETCH is not a further encapsulation of Ajax, but rather native JS that does not use XMLHttpRequest objects.

Advantages of Fetch:

  • Syntax concise, more semantic
  • Standards-based Promise implementation that supports async/await
  • More low-level, provide rich API
  • From the XHR

Disadvantages:

  • Error only for network requests, not for status codes returned by the server
  • Fetch (URL, {credentials: ‘include’})
  • Fetch does not support abort and timeout control. The timeout control implemented by setTimeout and Promise.reject cannot prevent the request process from continuing to run in the background, resulting in waste of traffic
  • Fetch has no way of natively monitoring the progress of requests, whereas XHR does

11. What are the methods of lazy loading of Javascript scripts?

Lazy loading means to load JavaScript files after the page is loaded. Lazy loading of JS helps to improve the speed of page loading

Generally, there are the following ways:

  1. The defer attribute: Add the defer attribute to the JS script. This allows the script to be loaded and the document to be parsed at the same time, and then execute the script file after the document is parsed, so that rendering of the page is not blocked. Several scripts that have the defer property set end up executing sequentially according to the spec, but this may not be the case in some browsers (keywords: synchronous, sequential)
  2. Async property: Add async property to the JS script. This property causes the loading of the script and the parsing of the document to be executed asynchronously. This property does not block the parsing of the page, but the execution of the JS script immediately after the script is loaded will also block if the document is not parsed. The order of scripts with multiple Async properties is unpredictable and generally does not follow the order of the code. (Keywords: asynchronous, may block, out of order)
  3. Dynamic CREATION of DOM: Dynamic creation of DOM tags, you can listen for the document loading event, after the document is loaded, you can dynamically create script tags to import JS scripts
  4. Use setTimeout delay: Set a timer to delay loading JS script files
  5. Loading JS files last: Place JS scripts at the bottom of the document so that JS scripts are loaded and executed as last as possible

12.CommonJS and ES6 module similarities and differences?

The difference between:

  • CommonJS is a shallow copy of the module, ES6module is a reference to the module; That is, ES6 cannot change the value of a pointer, which is equivalent to const
  • When the import interface is read-only, its variable value cannot be modified. That is, the address pointing of a variable cannot be changed, but the value inside the variable can be changed. You can reassign to CommonJS (change pointer pointer)

Thing in common:

Both CommonJS and ES6 Modules can assign values to imported objects, that is, change the values of the internal properties of the object