JavaScript (JS) is a lightweight, function-first, interpreted (directly parsed as text by the browser) or just-in-time compilation programming language. Although it is best known as a scripting language for developing Web pages, it has also been used in many non-browser environments, such as Node.js, Apache CouchDB, and Adobe Acrobat. JavaScript is a dynamic scripting language based on prototyping, multi-paradigm programming, and supports object-oriented, imperative, and declarative (such as functional programming) styles.

1. Data types

There are six data types in JavaScript.

  • Numbers: integers and decimals (such as 1 and 3.14).
  • String: text (such as Hello World).
  • Boolean: Two special values that indicate true and false, namely true and false.
  • Undefined: undefined or does not exist.
  • Null: indicates the null value, that is, the value here is empty.
  • Object: A collection of values.

Often, the three types — numeric, string, and Boolean — are called primitive type values, meaning they are the most basic data types that can’t be subdivided. Objects are called complex type values, because an object is often a composite of values of multiple primitive types and can be viewed as a container for various values. As for undefined and null, they are generally treated as two special values. Objects are the most complex data types and can be divided into three subtypes.

  • Object in a narrow sense
  • Array
  • Function (function)

Data type determination method

  • The typeof operator
  • The instanceof operator
  • Object. The prototype. The toString method
// The instanceof operator distinguishes an array from an object. var o = {}; var a = []; o instanceof Array // false a instanceof Array // true typeof null // "object" typeof NaN // 'number'Copy the code

Null is of type Object for historical reasons. The first version of the JavaScript language, in 1995, was designed with just five data types (object, integer, float, string, and Boolean) and didn’t consider null, treating it as a special value of object. Later, null is separated as a separate data type. In order to be compatible with previous code, the object returned by Typeof NULL cannot be changed.

NaN is not a separate data type, but a special numeric value

Two, prototype chain

A written explanation

JavaScript is often described as a prototype-based language — each object has a prototype object that takes its prototype as a template and inherits methods and properties from that prototype. A stereotype object may also have stereotypes from which it inherits methods and properties, layer by layer, and so on. This relationship is often called a prototype chain.

Popular accounts

Each object has a __proto__ property equal to the prototype of its parent constructor. When we access a property of obj, if the object does not have this property, we continue to look for obj.__proto__, which means that the parent constructor of obj does not have this property. __proto__.__proto__ ¶ If obj.__proto__ does not have this property, then continue to look for obj.__proto__. Returns undefined. This chain of objects linked by __proto__ is called a prototype chain.

Some useful points

create()

When we create an instance using the object.create () method, we can set who the new instance Object is modeled on.

function Person(first, last, age, sex, interests) {
    this.first = first;
    this.last = last;
    this.age = age;
    this.sex = sex;
    this.interests = interests;
}
var person1 = new Person('Bob', 'Smith', 32, 'male', ['music', 'skiing']);
var person2 = Object.create(person1);
console.log(person2.__proto__); // person1
Copy the code

The constructor property

Each instance object inherits a constructor property from the stereotype, which points to the constructor used to construct the instance object. (constructor (Chinese meaning “construction unit”), save information about the creator of the current instance object)

var person2 = Object.create(person1);
person2.constructor
person2.constructor.name // person1
person1.constructor.name // Person
Copy the code

Call () and the apply ()

Each function contains two non-inherited methods that do the same thing. They both call the function from a specific scope, which is equivalent to setting the value of the this object in the function body to expand the scope in which the function runs.

In general, this always points to the object that called a method, but when you use the call() and apply() methods, you change the orientation of this.

Differences: Different ways to receive parameters.

  • The apply() method takes two arguments, one is the scope (this) in which the function runs, and the other is an array of arguments.

apply([thisObj [,argArray] ]);

  • The first argument to the call() method is the same as that to the apply() method, but the arguments passed to the function must be listed.

call([thisObject[,arg1 [,arg2 [,...,argn]]]]);

function add(c,d){ return this.a + this.b + c + d; } var s = {a:1, b:2 }; The console. The log (add. Call (s, 3, 4)); // 1+2+3+4 = 10 console.log(add.apply(s,[5,6])); / / 1 + 2 + 5 + 6 = 14Copy the code

Reference blog.csdn.net/ganyingxie1…

3. Scope

Js scopes can be divided into global scopes and local scopes within functions

Declare a variable

Variable declarations, wherever they occur, are processed before any code is executed. The scope of a variable declared with var is its current execution context, which can be nested functions or global for variables declared outside any function. When assigning to an undeclared variable, the variable is implicitly created as a global variable after the assignment (it becomes a property of the global object).

Variable ascension

Since variable declarations (and other declarations) are always processed before any code is executed, declaring variables anywhere in the code is always equivalent to declaring them at the beginning of the code. This means that variables can be used before they are declared.

Var and let declare the difference between variables

Var declares that variables have variable promotion, but let does not. Variables declared by var can be declared more than once; let cannot

Fourth, the closure

concept

A closure is a combination of a function and the scope object it was created with.

function makeAdder(a) { return function(b) { return a + b; } } var add5 = makeAdder(5); var add20 = makeAdder(20); add5(6); // 11 add20(7); / / 27Copy the code

Every time JavaScript executes a function, a Scope Object is created to hold the local variables created in the function. It is initialized with all the variables passed into the function (and after initialization, it contains all the variables passed into the function). This is similar to global objects that hold all global variables and functions, but there are some important differences. First, each time a function is executed, a new, scope-specific object is created. Second, unlike global objects (such as the browser’s Window object), you cannot access scope objects directly from JavaScript code, and there is no way to iterate over properties in the current scope object.

Normally, the JavaScript garbage collector will reclaim the scope object created by the external function (denoted as a) at this point, but the return value of the external function (the internal function) has a reference to the scope object A. Finally, the scoped object A is not collected by the garbage collector until there are no references to the inner function.

Pros and cons of closures

Advantages: 1. The scoped object of the closure does not pollute the global object.

Disadvantages: 1, closure will make the variables in the function are saved in memory, memory consumption is very large, may cause web page performance problems, even memory leaks. 2, It is possible that this is the problem

The purpose of closures

1. Closures can read local variables in the scope of a function externally

function f1(){ var n=666; function f2(){ console.log(n); } return f2; } var result=f1(); result(); / / 666Copy the code

2. Keep local variables in memory and will not be automatically cleared. It can be used to cache data.

Function f1(n) {var cache = {} return {f2: Function () {if(cache[n]) {// Cache exists, Directly back to the console. The log (" = = = = = = = > go cache ') return the cache [n].} the console log (' = = = = = = = > assignment ') var p = 'test' cache [n] = p return p}}} Var (' 1 ') a = f1 a.f () / 2 / "test" = = = = = = = > assignment a.f () / 2 / "test" = = = = = = = > go cache / / the code above, the function of the local variable n f1 kept in memory, not in f1 is automatically cleared after the call. Imagine / / f2 is a process is very time consuming function object, each invocation will take a long time, so we need to calculate the value of the stored, when this function is called, in the first place in the cache lookup, if can't find, is calculated, and then update the cache and return values, if found, directly to return value to find.Copy the code

3. Encapsulate the private properties and methods of an object.

function f1(n) { return function () { return n++; }; } var a1 = f1(1); a1() // 1 a1() // 2 a1() // 3 var a2 = f1(5); A2 () // 5 A2 () // 6 a2() // 7 // in this code, a1 and a2 are independent of each other, each returns its own private variable.Copy the code

Five, events,

Events are not a core part of JavaScript — they are defined in the browser’s Web APIs

Web event

  • Event Handler properties
const btn = document.querySelector('button');

btn.onclick = function() {
  const rndCol = 'rgb(' + random(255) + ',' + random(255) + ',' + random(255) + ')';
  document.body.style.backgroundColor = rndCol;
}
Copy the code
  • Inline time processor

Also known as inline event handlers, they are considered bad practice. Mixing HTML and JavaScript makes documents difficult to parse and less search engine friendly.

<button onclick="alert('Hello');" >Press me</button>Copy the code
  • AddEventListener and removeEventListener

Event listening has many advantages. You can use removeEventListener() to remove the event handler code if needed, and you can add more than one listener to the same type of element if needed.

The event object

Inside the event handler, you might see a parameter with a fixed name, such as Event or e. This is called an event object, and it is automatically passed to the event handler to provide additional functionality and information. The target attribute of the event object E is always the element where the event just occurred.

Prevent default behavior

preventDefault()

Event bubble and capture

The execution of events in JS must go through two stages: capture and bubble

Capture – The browser checks whether the element’s outermost ancestor, < HTML >, registered an onclick event handler during the capture phase, and if so, runs it. It then moves to < HTML > and clicks on the element’s next ancestor and does the same, then clicks on the element and the next ancestor, and so on, until it reaches the element that was actually clicked.

Bubbling – The browser checks whether the actually clicked element registered an onClick event handler during the bubbling phase, and if so, runs it. – Then it moves to the next immediate ancestor element and does the same, and then the next, and so on, until it reaches the < HTML > element.

To stop bubbling — e.topPropagation ();

Using the event bubbling mechanism, we can also implement event delegation. For example, if we want to run a piece of code by clicking on any of the large elements, we can set event listeners on the parent node and have events occurring on the children bubble up to the parent node, rather than setting event listeners separately for each child node.

Six, asynchronous

Javascript is a “single-threaded” language that can only do one task at a time; if you have multiple tasks, you must queue. The Javascript language divides tasks into two modes of execution: Synchronous and Asynchronous.

The mechanism for asynchronous execution is as follows

(1) All synchronization tasks are executed on the main thread, forming an execution context stack. (2) There is a “task queue” in addition to the main thread. Whenever an asynchronous task has run results, an event is placed in the “task queue”. (3) Once all the synchronized tasks in the “execution stack” are completed, the system reads the “task queue” to see what events are in it. The corresponding asynchronous tasks then end the wait state, enter the execution stack, and start to execute. (4) The main thread repeats the third step above.

Four methods of asynchronous programming

  • The callback function

This is the most basic method of asynchronous programming. Callbacks are code that hangs on the main thread. An asynchronous task must specify a callback function, which is executed when the main thread starts executing the asynchronous task.

  • Event listeners

Event-driven mode is adopted

  • Publish/subscribe pattern (Observer pattern)

When a task is completed, it “publishes” a signal to the signal center, and other tasks can “subscribe” to the signal center to know when they can start.

  • Promise object

Each asynchronous task returns a Promise object with a THEN method that allows you to specify a callback function.

One of the features of the JavaScript language is that it is single threaded. That is, you can only do one thing at a time. So why can’t JavaScript have multiple threads? That will improve efficiency. JavaScript is single threaded, depending on what it’s used for. As a browser scripting language, JavaScript’s primary use is to interact with users and manipulate the DOM. This determines that it has to be single threaded, otherwise it will cause complex synchronization issues. For example, if JavaScript has two threads at the same time, one adding content to a DOM node and the other removing the node, which thread should the browser use? So, in order to avoid complexity, JavaScript has been single-threaded since its inception, and this has been a core feature of the language and will remain so.

Reference: JavaScript running mechanism a: talk about the Event Loop www.ruanyifeng.com/blog/2014/1…

Seven, regular

Regular expressions are objects that describe character patterns. For string pattern matching and retrieval replacement, is a powerful tool for string pattern matching.

There are several important points to learn regular expressions: syntax, modifiers (I, g, m), square brackets ([]), metacaracters, quantifiers, and object methods (test, exec).

grammar

var re = new RegExp("\w+");
var re = /\w+/;
Copy the code

Object methods

The test() method checks if a string matches a pattern, returning true if the string contains matching text, and false otherwise.

var patt = /e/; \ patt.test("The best things in life are free!" ); // trueCopy the code

Exec () returns an array of matched results. If no match is found, null is returned.

var patt = /e/ patt.exec('the first apple is red! '); // ["e", index: 2, input: "the first apple is red!", groups: undefined]Copy the code

Reference: www.runoob.com/jsref/jsref…

Object oriented Programming (OOP)

The basic idea of OOP is that in a program, we use objects to model the real world, simplifying and providing access to functionality that would otherwise be difficult (or impossible) to use. Classes and instances are the basic concepts of most object-oriented programming languages, but JavaScript does not distinguish between classes and instances. Instead, it implements object-oriented programming through prototypes.

features

  • encapsulation

The first meaning is that the attributes and behaviors of objects are regarded as an inseparable whole. The second meaning is that the attributes and implementation details of objects are hidden and only public access methods are provided to isolate changes, facilitate use, and improve reusability and security.

  • inheritance

Improve code reusability; Inheritance is a prerequisite for polymorphism.

  • abstract

Abstraction is a mechanism that allows the simulation of generic parts of a working problem. This can be done by inheritance (reification) or composition. JavaScript instantiates through inheritance, by having instances of classes be property values of other objects to achieve composition.

  • polymorphism

A reference variable to a parent class or interface definition can point to an instance object of a child class or concrete implementation class. Improves the extensibility of the program.

Reference: developer.mozilla.org/zh-CN/docs/…