First of all, we want to master the basic knowledge, it is necessary to try to comb knowledge points! This step is important to have a tree of knowledge in mind.

Briefly comb the basic knowledge points:

  • Variable types
Js data type classification and judge value type and reference typeCopy the code
  • Stereotypes and stereotype chains (inheritance)
The definition of stereotypes and stereotype chains is written as inheritanceCopy the code
  • Scope and closure
What is the execution context this closureCopy the code
  • asynchronous
Synchronous vs Asynchronous Asynchronous and single-threaded front-end asynchronous scenariosCopy the code
  • The examination of new es6/7 standard
Arrow functions such as Module Class Set and Map Promise..........Copy the code

Knowledge combing

After building the basic knowledge system, we can improve the knowledge system in detail

Variable types

Js is a weak type scripting language, which does not need to define the type at the time of definition, and will automatically judge its type in the process of program running.

6 primitive types in ES:
  • Null
  • Undefined
  • String
  • Number
  • Boolean
  • Symbol (new) ES6
typeof

Typeof returns values of the following types: undefined Boolean number String object function, symbol

It is worth noting: Typeof Symbol(); typeof Symbol(); typeof Symbol(); This is a new knowledge point in ES6Copy the code
instanceof

If a variable is an Array, use [1, 2] instanceof Array instead of typeof. Because, [1, 2] is an Array, its constructor is Array

Value type vs reference type

Value type variables include Boolean, String, Number, Undefined, Null, and reference types include all Object types. Such as Date, Array, Function, etc.

In terms of parameter passing, value types are passed by value (assignment to other variables does not change the original value), and reference types are passed by share (assignment to other variables actually shares the address, and changes to other variables also cause values in the heap to change because they point to the same address).

The reason for this design in JS is that a copy of the type passed by value is stored in the stack memory, which generally does not take up too much memory, and passing by value ensures its access speed. The type passed by share is to copy its reference, not the entire value (pointer in C language), to ensure that objects that are too large do not cause memory waste by constantly copying content. Var obj = {a: 1, b: [1,2,3]} var a = obj.a var b = obj.b a = 2 b.ush (4) console.log(obj, a, b)Copy the code

Prototype and prototype chain

The prototype
  • JavaScript is a prototype-based language, and there are four things to keep in mind:
  1. All reference types (arrays, objects, functions) have object properties and are free to extend attributes (except null)
  2. All reference types (arrays, objects, functions) have an _ proto _ attribute whose value is an ordinary object
  3. For all reference types (arrays, objects, functions), the _ proto _ property value points to the prototype property value of its constructor (instance._ proto _ === constructor. Prototype).
  4. All functions have a prototype property whose value is also a normal object
  • When trying to get a property of an object, if the object doesn’t have the property itself, it looks in its _ proto _ (the prototype of its constructor)
  • Use hasOwnProperty to determine if this property is a property of the object itself:

Advanced browsers already block attributes from prototypes in for in, but sometimes prototype judgments can be added to ensure robustness:

F. hasownProperty (item) => Check whether item is an attribute of the f object itselfCopy the code
Prototype chain

When trying to get an attribute of an object, if the object doesn’t have the attribute itself (toString), it looks in its _ proto _ (the prototype of its constructor). If you don’t find toString in F. _ proto _, then proceed to F. _ proto _._ proto _ is foo.prototype. _ proto _.

If you go all the way up, you’ll find a chain, so it’s called a prototype chain. If the topmost layer is not found, it fails and returns undefined. What’s at the top? Object.prototype._ proto _ === null

This in the prototype chain

Very complicated! Please look at the description of this in my previous articles

Scope and closure

Execution context
Before executing a javascript script (i.e. a <script> tag), the code is parsed. When parsing, a global execution context is created. Because you don't know when the function will be executed. The variable is temporarily assigned to undefined, and the function is declared ready to use. This step is done, and then the formal execution of the procedure begins. Again, this is work before the code executes. Before a function is executed, a function execution context is also created, similar to the global context, except that the function execution context includes this arguments and function argumentsCopy the code

To summarize: Scope: executable JS code Global context: variable definition, function declaration Function context: variable definition, function declaration, this, arguments

this

The value of this is checked at execution time, not at definition. Because this is acknowledged when performing context creation

Note several usage scenarios: constructor, object property execution, normal function execution, call, apply, and bind to change pointing

scope

Originally JS had no block-level scope, only global scope and function scope. But there is a risk of contamination exposure. So we use jQuery, Zepto, etc libraries in (function(){…. })() private variables to prevent memory leaks.

ES6 started to add block-level scope, using let to define variables

The scope chain

Free variables: variables that are not defined in the current scope. The value of a free variable can only be found in the parent scope. This layer of relationship is the scope chain. Also, the scope chain is created when the pointing context is created, so the scope chain is determined when the variable is defined.

closure

Closures occur when {} blocks or functions have internal functions that reference external variables

asynchronous

Synchronous vs Asynchronous
  • Asynchrony: does not block the running of subsequent programs and can be performed simultaneously with other timelines
  • Synchronization: like a queue of people, can not jump the queue, can only come one by one, the front will block the back of the program
Asynchronous and single threaded

Js is a single thread running, can only do one thing at a time, not “dual use”.

Var a = true; setTimeout(function(){ a = false; }, 100) while(a){console.log('while executing ')} // Qishi Henduor yiwei Zheli hui 100MSZHIhou // Since js is single threaded, there is no time thread to run the timer after entering while, so it is an infinite loopCopy the code
Front-end asynchronous scenario

A lot of things ~ timer delayers, network requests, IMG loads, Ajax and so on

Console. log('start') var img = document.createElement('img') // img = new Image() img.onload = function () { console.log('loaded') img.onload = null } img.src = '/xxx.png' console.log('end')Copy the code

The examination of new es6/7 standard

Arrow function

The arrow function is the new function definition form defined in ES6

Function name (a1,a2) {… } can be written as (a1,a2) => {… }

There are some differences between the arrow function and the traditional one. See my other article, which explains in detail that the arrow function is simpler to write, and it can also solve the problem that this was a global variable before es6.

function fn() { console.log('real', this) // {a: Var arr = [1, 2, 3] // ordinary JS arr.map(function (item) {console.log(' JS ', this) // window. Return item + 1}) // Arrow function arr.map(item => {console.log('es6', this) // {a: 100}. This return item + 1})} fn. Call ({a: 100})Copy the code
Module

The modularity syntax in ES6 is more concise

// Create util1.js file, export default {a: 100} // create index.js file, import obj from './util1.js' console.log(obj)Copy the code

If you want to output multiple objects, you can’t use default and import {… }, we usually do this when we write an API, when we call the introduction interface, and we also introduce some components and methods, so we can simplify the code

// 创建 util2.js 文件,内容如
export function fn1() {
alert('fn1')
}
export function fn2() {
alert('fn2')
}
// 创建 index.js 文件,内容如
import { fn1, fn2 } from './util2.js'
fn1()
fn2()

Copy the code
Class

What’s the difference between a class and a normal constructor?

Class was actually a JS keyword (reserved word), but was not officially used until ES6. ES6’s class replaces the previous constructor to initialize an object, which is syntactically more object-oriented. Let me show you two examples:

Function MathHandle(x, y) {this.x = x; this.y = y; } MathHandle.prototype.add = function () { return this.x + this.y; }; var m = new MathHandle(1, 2); Console. log(m.addd ())) // ES6 class constructor {constructor(x, y) {this.x = x; this.y = y; } add() { return this.x + this.y; } } const m = new MathHandle(1, 2); console.log(m.add())Copy the code

Here are five things to note about class:

  1. Class is a new syntax, class Name {… } in this form
  2. In contrast, the body of a class’s constructor is written in constructor, which is executed by default when the instance is initialized
  3. Add (){… }, there is no function keyword
  4. Extends is used to implement inheritance and is more in line with object-oriented language writing
  5. The constructor of a subclass must execute super() to call the constructor of its parent class

Let me show you two examples:

  • Javascript constructor implementation inheritance:
Function Animal() {this.eat = function () {console.log(' Animal eat')}} // Dog() {this.bark = Function () {console.log(' bark')}} prototype = new Animal() var hashiqi = new dog () The console. The log (hashiqi) / / {bark: ƒ (), __proto__ : Animal}Copy the code
  • Inheritance of ES6 class implementation
class Animal { constructor(name) { this.name = name } eat() { console.log(`${this.name} eat`) } } class Dog extends Animal { constructor(name) { super(name) this.name = name } say() { console.log(`${this.name} say`) } } const dog = new Dog(' husky ') dog.say() dog.eat()Copy the code
The Set and Map

Set and Map are new data structures in ES6. They are extensions of the current JS array and object data structures.

  • A Set is similar to an array, but an array can contain duplicate elements, but a Set cannot contain duplicate elements and will be automatically filtered out
  • A Map is similar to an object, but the key of an ordinary object must be a string or a number. The key of a new Map can be any data type.
  1. A Set instance does not allow elements to be duplicated, even if you add elements internally through it
  2. The five properties and methods of the Set instance
Add (value) : adds an element to an array, and returns the Set instance itself. Delete (value) : deletes an element from the array. Returns a Boolean indicating whether the deletion was successful. Clear () : Clears all elements with no return valueCopy the code
  1. Set instance traversal:
Keys () : iterator for returning key names values () : iterator for returning values, keys () and value () return the same result because Set has no key names, only keys () entries () : iterator for returning key and value pairs forEach () : iterator forEach member using a callback functionCopy the code
  1. Map

Map.set (obj, ‘OK’) is a key that uses objects (not just objects, but any data type)

  1. Map instance 6 properties and methods:
Size: obtains the number of members set: sets the key and value GET: obtains the attribute values of a member. Has: determines whether a member exists. Delete: deletes a memberCopy the code
  1. The Map instance traversal methods are:
Keys () : returns a traverser for key names. Values () : Iterator that returns key values. Entries () : Returns a traverser for all members. ForEach () : traverses all Map members.Copy the code
Promise

Promise is a specification from CommonJS that allows callbacks to be written as chained calls, making the flow cleaner and the code more elegant.

Promise: three states, two processes, and one method: pending, depressing, and Rejected This will be a big pity (pity) or a big pity (pity). This will be a pity (pity) or a pity (reject).Copy the code

conclusion

This article summarizes some knowledge points that are often investigated in ES basic grammar. As the front end, these basic knowledge points should be mastered. Moreover, my summary is relatively shallow, so interested students can learn it in depth