1. First things first

Recently has been from the principle to understand the JS foundation, found that his goods quite abundant. It used to be easy to touch a rational article or blog, but lately it feels refreshing to get down to the basics of language design. Some rules and design are also designed to solve problems and solve problems efficiently. A language is also a programmer’s tool, the use of a good tool is not only to understand the specification (API), application language API, must understand the characteristics of the language and temperament, so that the use will be free, in order to give full play to its maximum potential.

Know yourself and know your enemy well.

For example, JS is a purely interpretive language at the beginning. The parser of JS virtual machine converts the source code into intermediate code, and then directly uses the interpreter to execute the intermediate code, and then directly outputs the results.

The principle of JS parsing is the same, but there are several kinds of JS virtual machines, and there are some differences between them: Apple’s javaScriptCore virtual machine in Safari, Firefox’s TraceMonkey virtual machine, and Google’s V8 virtual machine

How does V8 execute JS code? V8 is a hybrid of compiler execution and interpreter execution. The technique of mixing compiler and interpreter is called JIT (Just In Time)

So I think JS is interpreted language, just to optimize js running speed, mixed with the compiler in time compilation technology. “You don’t know JS” said js is a compiled language, a bit ambiguous, can not better explain the core principle of modern JS.

MDN is expressed very accurately, feeling that MDN is the best place to learn the standard specification JS:

JavaScript is a function-first, lightweight, interpreted or just-in-time compiled programming language.

This expression summarizes so many norms, so beautiful. It all looks good. It’s all dry

Learn about the language features from V8 parsing javaScript

1. Feature 1:First class citizens

Js functions can be assigned as variables, and can be passed as a parameter to another function, which returns another function. First-class citizen design, you have closures, you have functional programming, and so on.

When you use a function to assign, pass, or return a reference to an external variable, you need to make sure that the referenced external variable exists. This makes the function a first-class citizen, because the virtual machine also needs to handle the external variable referenced by the function.

So when JS was created, if we want to support functions as first-class citizens, we must have the emergence of lexical scope. With the characteristics of lexical scope and first-class citizens of functions, closures are naturally their products. It’s not js to create closures.

Closure is the binding of function and its external environment, JS developers use this feature for concise code writing, so third-party code is a lot of use, can make their own code more concise. So understanding closures is the basis for reading third-party source code.

2. Characteristic 2:Functions and objects

Js is a language based on object, most of the content is composed of objects, these objects can dynamically modify the content, that created js is a super flexible language, increase the difficulty to understand and use the language In js Function is an object, Function also have attributes and values, we declare the Function prototype is object Function, This is created by the Function constructor. There is also the main public property of prototype inheritance, Prototype. V8 uses these two hidden attributes to implement the function callable feature. -name: is the name of the function. If the function is not set, the name of the function is the common anonymous function. Represents the function code, stored in memory as a string. When a function call statement (function name in parentheses) is executed, V8 retrieves the value of the code property from the function object, which is the function code, and then interprets the execution of the function code

If the value of an attribute in an object is a function, we call that attribute a method, so we say that an object has properties and methods.

3. Feature 3: Object attributes are divided intoSort propertiesGeneral properties

Object has two hidden properties, Element and Properties pointing to the Elements object and properties property, respectively

Sort attributes (Elements) : Properties of an object whose property name is number are sorted in ascending order by index value. General properties: Properties of an object whose property name is string are called general properties and sorted in ascending order by creation time

V8, in order to improve the performance of storing and accessing these properties, uses two linear data structures. V8 reads all elements sequentially from the Elements property and then reads all elements from the Properties property, thus completing an index query for object properties.

If you index the properties property, you will first use the hidden properties property to find the properties object, and then you will find the property in the properties object. V8 then, in addition to an optimization strategy, stores some general properties directly into the object itself, called in-object properties. The number of properties in the object is fixed. The default is 10. If the object has 10 more general properties, the remaining general properties are placed in the general property object.

Properties are stored using linear structures, also known as fast properties. Looking up properties is very fast. Linear structures take a lot of time and memory to delete and add properties. When there are too many general attributes, some attributes are stored in properties, where the storage strategy is slow attribute strategy, nonlinear data structure storage (dictionary).

4. Characteristics 4:Function expressions and call-now function expressions (IIFE)

Function expressions and function declarations

Var fun = function() {} var fun = function() {}

There is a function declaration, js is also allowed but function declarations cause a variable promotion problem

func()
function func() {console.lohg('I output')}
Copy the code

The above code works, but

func1()
func1 = function() {console.log('I output')}
Copy the code

This code will report an error

VM130:1 Uncaught TypeError: func1 is not a function at :1:1
Copy the code

Why? Well, you have to understand expressions and statements, scope, compile phase, execute phase.

Remember: function expressions are expressions and function declarations are statements. Js only parses statements in the compile (parse) phase, with no output. However, related variables are put in scope and parsed statements are not executed. In the execution phase as long as there is the variable scope can be used, so the func () function normal operation Also is to know why why when using the function expression to this wrong, because at the time of compilation phase, foo the variable is undefined is a native object rather than a function, so this line of code to perform this error

Call the function expression immediately

If you replace a=3 with a function, because () can only contain expressions, the function is considered to be a function expression, An expression that returns a function object at execution time (found in scope) is a function call enclosing a parenthesis (), and the function inside the parenthesis is executed immediately. Such an expression is called an immediate call

Because immediately call a function expression is an expression, so V8 in compilation phase, is not a function object to this expression, the expression of properties and methods will not be accessed by other code, wouldn’t the global environmental pollution js, before ES6, js no private scope, the concept of modularity, Can cause your module’s variables to overwrite others’ variables, so use immediate call function expressions, wrapped, to avoid variable contamination between each other.

5. Features:Prototype inheritance

Language inheritance is simply said that an object can access the properties and methods of another object, JS is the use of prototype inheritance strategy

The js object has a hidden property that Proto calls the object’s prototype. This property points to another object in memory, which is the prototype object. That object has access to its prototype’s methods and properties

There are some inheritance schemes out there that are annoying with a lot of names, but you can be confused by them without knowing what they are. 3. Combinatorial inheritance (combinatorial inheritance and borrowed constructor inheritance) (common), 4. Parasitic inheritance 5. Parasitic combination inheritance, 6. Primary inheritance

Constructor: The property is passed as an argument. Inside the function, this sets the value of the property.

function DogFactory(type,color){
    this.type = type
    this.color = color
}
Copy the code

Then combine the keyword new to create the object.

var singleDog = new DogFactory()
Copy the code

V8 (JS virtual machine) returns an object when using the new keyword with a function. You can do your own search

New Essence, V8 does these things:

var dog = {}
dog.__proto__ = DogFactory.prototype
DogFactory.call(dog, 'Dog'.'Black')
Copy the code

As shown in figure:

This is to create an empty object, point the empty object’s prototype to the public property of DogFactory function, and call the empty object with the empty object dog. In this way, dog is the constructor’s this. The constructor will fill the property and finally create the dog object. There’s actually an inheritance going on here as well, so we said that functions are objects, so constructors are objects, and our generated object dog inherits the properties of the constructor, so it’s kind of prototypical inheritance.

If we can implement some inheritance based on the concept of inheritance,

Prototype chain inheritance: This is done by pointing the child’s constructor’s prototype to the parent (whenever this function is used as a constructor to create an object, the function’s prototype points to the object’s prototype)

Worker.prototype = new Person(); worker.prototype = new Person();

Call (this, name, age); person.call (this, name, age);

Combinatorial inheritance: All of the above code causes performance and inheritance traceability issues (V8’s assigned prototype object destruction and constructor pointing mess). There is also a common constructor property on the prototype object. This property points to the constructor, whose prototype points to the prototype object Use call to replace the constructor’s this key code: js person.call (this, name, age); Worker.prototype = new Person(); Worker.prototype.constructor = Worker; Function Empty(){}; Empty.prototype = o; Js var woker={name: ‘jia’, age: 18, job: ‘job’} var mine = object.create (woker); In the same way, ECMAScript 5 normalizes primitive inheritance by adding the object.create () method. Parasitic inheritance: that is, the original type inheritance covers a shell

Parasitic combinatorial inheritance: it is the most effective way to realize type-based inheritance by combining the advantages of both parasitic and combinatorial inheritance

The __proto__ constructor inherits these concepts, and the inheritance problem is solved easily. Do you have to prepare so many inheritance methods, do you have to memorize the code, see the essence, you can slowly talk to the interviewer

The above inheritance has many performance problems (which you can check out), and parasitic combinatorial inheritance is the optimal solution before ES6 inheritance. In ES6, the class keyword extends is a syntactic sugar, but it also provides a uniform and optimal solution for inheritance. Maybe some compatibility issues, but Babel, what the hell!!

Property 6: Chain of scopes

JsS is based on lexical scope, which means that the order in which scopes are searched is determined by where functions are defined.

Variables are searched in the order of the current function scope -> global scope path

Function scope: Each function needs to find its scope during execution. When a variable is used in a function or a function is called, the function scope is searched first. After the function completes execution, the scope is destroyed

Global scope: A global scope is created during V8 startup and remains in memory undestroyed until V8 exits

If the variable is not found in the current function scope, V8 will go to the global scope to look up the variable, which is called the scope chain

First, when V8 starts, global scopes are created, including variables like this and window, as well as some global Web API interfaces.

Feature 7 Type conversion 1 + ‘2’? 3: ’12’

In the simple expression of the title, two different types of data are added. To sort out the above two problems, we should know the concept of type, JS operation type strategy

In high-level languages, data for operations is assigned a specific type, which confirms that a value or group of values has a specific meaning and purpose.

Every computer language defines its own types, and it defines how to operate on those types, and it defines how those types should interact, and we call that a type system, right

V8 has a ToPrimitve method that converts a and B to native datatype. The conversion process is as follows:

  • If valueOf does not return the primitive type, the toString method is used to return the value.
  • If neither method returns a primitive type value, a TypeError error is raised;

If you still don’t understand (take the time to understand), you can be sure that V8 will use the ToPrimitve method to convert object types to native types. If one is worth a string, the other value needs to be converted to a string, and then the other value needs to be converted to a string and then concatenated. In other cases, the value is converted to a numeric value and then added. Go to the interview, hahaha.

Interview a shortcut

There is no shortcut to an interview. Be sure to understand the nature of the language, to understand the characteristics and basic strategies of the language from the principle. That’s how you win every battle. Refueling, I am parallel goods, cheat traffic, above are notes (he is not notes, did not read it, once turned over)