You don't know, javascript-. Book notes

Source: Internet
Author: User
Tags access properties closure

This book is mainly elaborated from two parts: scope and Closure, this and object prototype.

One-scope and closed-packet

1-scope

For JavaScript, most of the time the compilation occurs in a few subtle times before the code executes. Behind the scopes we're talking about, the JavaScript engine is trying to make the best performance possible, such as JIT, which can delay compilation or recompilation.

The engine is responsible for compiling and executing the entire JavaScript program from beginning to end.

compiler = responsible for parsing and code generation

Scope = = is responsible for collecting and maintaining a series of queries consisting of all the declared identifiers and enforcing a set of strict rules that determine the access rights of the currently executing code to these identifiers.

Assignment of variables: first the compiler declares a variable in the current scope (if it was not previously declared), and then the runtime engine finds the variable in the scope and assigns it to it.

LHS: LHS Query When a variable appears to the left of an assignment operation. Who is the target of the assignment operation (LHS)

RHS: RHS Query When a variable appears to the right of an assignment operation. Who is the source of the assignment operation (RHS)

Scopes are a set of rules that look up variables by name, to determine where and how to find variables. If the purpose of the lookup is to assign a value to a variable, the LHS query is executed, and if the purpose of the lookup is to get the value of the variable, the RHS query is executed. An assignment operation causes the LHS query to be queried. = operator or an operation that passes in a parameter when the function is called will result in an assignment of the associated scope. When a function is nested within another function, a nested nesting of scopes occurs. Therefore, when a variable is not found in the current scope, the engine will continue to look in its nested outer scope until the variable is found or the outermost scope is reached.

An unsuccessful RHS reference causes the Referenceerror exception to be thrown. An unsuccessful LHS reference causes a global variable to be automatically created implicitly (in a non-strict mode) that uses the target referenced by the LHS as an identifier, or throws a Referenceerror exception (in strict mode).

2-Lexical scopes

Lexical scope: Defines the scope in the lexical stage, which is determined by where you write the variable and function scope when you write the code, that is, where the function or variable declaration is located.

3-Function scope

function scope: All the variables that belong to this function can be used and reused throughout the scope of the function.

You can wrap variables and functions in the scope of a function, and then use that scope to hide them. This avoids collisions between identifiers of the same name, and can also serve to protect internal variables and functions.

Function declaration: function is the first word in a declaration; The main difference between a function declaration and a function expression is where their name identifiers will be bound.

anonymous function expression: No name identifier. Cons: Anonymous functions do not display meaningful function names in stack traces, making debugging difficult, detrimental to their own invocation, and not friendly to readability. Ps: Always name the function expression best practice.

Execute the function immediately: the function is contained inside a pair of parentheses, thus becoming an expression that can be executed immediately by adding another () at the end of the function.

There are two ways to write functions immediately: 1. (function () {...}) () 2. (function () {...} ())

Ps: Execute function immediately you can specify a function name or pass in a parameter.

Ps: Any variable declared within a scope will be attached to that scope.

4-Lifting

Functions and variable declarations are moved from where they appear in the code to the top of your scope, a process called Ascension.

Both function declarations and variable declarations are promoted, PS: function declarations are promoted first, and variable declarations are promoted.

The declaration itself is promoted, and the assignment operation, including the assignment of a function expression, is not promoted.

5-scope closure

Closure: A function executes outside its lexical scope, or it can discover variables outside the current lexical scope through closures.

    function foo () {         var a=2;         function Bar () {           console.log (a);      }        return bar;   }    var baz=foo ();    

PS: In timers, time listeners, Ajax requests, cross-window communications, WEB workers, or other asynchronous or synchronous tasks, a closure is actually used whenever a callback function is used.

for (Var i=1;i<=5;i++) {  setTimeout (function timer () {   console.log (i);},i*1000);}

This code will output 5 times per second at run time 6. The condition of the loop termination is I no longer <=5, when the condition is first established, the value of I is 6, So the end of the loop at the end of the I value is 6. Although the five functions in the loop are defined separately in their iterations, they are enclosed in a shared global scope and actually have only one I. In order to output 1 to 5 sequentially, there are several ways to do this:

(1) A variable is required to store the value of I in each iteration for       (var i=1;i<=5;i++) {  (function (j) {var j=i;settimeout (function timer ()    { Console.log (j);} , j*1000);}) ( );} (2) for (Var i=1;i<=5;i++) {(function (j) {SetTimeout (function timer () {  console.log (j);},j*1000);}) (i);}                     Ps: Use the immediate execution function in an iteration to generate a new scope for each iteration, so that the callback for the deferred function can enclose the new scope within each iteration, and each iteration contains a variable with the correct value for us to access. (3) for (Var i=1;i<=5;i++) {let   j=i;   SetTimeout (function timer () {   console.log (j);},j*1000);} (4) for (let i=1;i<=5;i++) {  setTimeout (function timer () {  console.log (i);},i*1000);}

The Ps:let declaration, which can be used to hijack a block scope and declare a variable in this block scope. Essentially, a block is converted into a scope that can be closed.

The settimeout () function is called in the Ps:for Loop, and the callback for the deferred function executes at the end of the loop.

Two this and the object prototype

About this

This is bound at run time, and its context depends on the various conditions when the function is called. The binding of this is not related to the location of the function declaration, only depends on how the function is called.

When a function is called, an activity record is created, also called the execution context, which contains where the function is called, how it is called, the parameters passed in, and so on.

This is the binding that occurs when a function is called, and what it points to depends entirely on where the function is called.

2-this Comprehensive Analysis

The call location is where the function is called in the code. Finding the call location is where the function is called. The most important thing is to parse the call stack.

function Baz () {///the current call stack is baz//the current call position is the global scope Console.log ("Baz"); bar ();   The call position of Bar}function Bar () {//Current call stack is baz->bar//current call position in Baz Console.log ("Bar"); foo ();  Foo's call Location}function foo () {//Current call stack is baz->bar->foo//current call position in bar Console.log ("foo");} Baz ();  Baz the call location

How the call location determines the binding object of this during the execution of the function requires finding the call location and then deciding which binding rule to apply.

Binding rules: Default bindings, implicit bindings, display bindings, new bindings

Default bindings: Standalone function calls

function foo () {  console.log (THIS.A);} var a=2;foo ();  2    

Implicit binding: You need to consider whether the call location has a context object, or whether it is owned or contained by an object. An implicit binding binds this to this context object in a function call. A property that contains a pointer to a function is included inside an object, and the function is indirectly referenced by this property to bind this indirectly (implicitly) to the object.

function foo () {  console.log (THIS.A);} var obj={  a:2,                      Foo:foo};obj.foo ();  2

PS: The object attribute reference chain has only the previous layer or the last layer to function in the call location.

function foo () {

Console.log (THIS.A);

}

var obj2={

A:42,

Foo:foo

};

var obj1={

A:2,

Obj2:obj2

};

Obj1.obj2.foo (); 42

Show Bindings: You can specify the context for the calling function by using the call or Apply method, specifying the binding object for this directly.

function foo () {  console.log (THIS.A);} var obj={  a:2};foo.call (obj);  2

New binding: Using new to invoke a function, or a constructor call, the following action is performed automatically = "(1) Create a completely new object (2) This object will be executed [[Prototype]] Connection (3) The Heart object will be bound to the function called this (4) If the function does not return another object, the function call in the new expression will automatically return the new object.

function foo (a) {  this.a=a;} var bar=new foo (2); Console.log (BAR.A);  2

Precedence comparison of bindings: New bindings Show bindings implicit binding default bindings

(1) is the function called by new? Yes, this binds to the newly created object.

var bar=new foo ();

(2) is the function called by call or apply or hard bind? Yes, the this binds to the specified object.

var bar=foo.call (OBJ2);

(3) is the function called in a context? Yes then this binds to that context.

var bar=obj1.foo ();

(4) If none of the above is the case, the default binding.

3-Object

Object definition in two ways: Declaration form, Construction form

Declaration form: var myobj={      Key:value} construction form: var myobj=new Object (); myobj.key=value;

The difference is that multiple key/value pairs can be added in declarative form, but they need to be added individually in the form of a construct.

Type: String, number, Boolean, null, Undefined, object

Built-in objects: String, Number, Boolean, object, Function, Array, Date, REGEXP, Error

Ps: These built-in functions can be used as constructors to construct a new object of the corresponding subtype.

Ps: When necessary, JavaScript automatically converts the string literal to a string object.

Ps:null and undefined do not have corresponding structural forms, and they perform declarative forms; Date is only constructed and has no declarative form.

Ps: For object, Array, Function, and RegExp, they are objects, either declaratively or in the form of a construct.

Content: The content of an object consists of some values stored in a particular named location, which we call attributes. Stored inside the object container are the names of these properties, which, like pointers, point to the actual storage location of those values.

How the property value is accessed:. operator or [] operator

Where. A is called a property access, ["a"] is called a key access. They access the same location and return the same value. In an object, the property name is always a string. Although a number is used in an array subscript, the number in the object property name is converted to a string.

Computable property name: Use [] to wrap an expression in a literal form as a property name.

var prefix= "foo", var myobj={  [prefix + "bar"]: "Hello",  [prefix + "baz"]: "World"};myobj["Foobar";  hellomyobj["Foobaz"];  World

Array:

      var arr=["foo", "a", "bar";             Arr.baz= "Baz";       Console.log (arr.length); 3       Console.log (Arr.baz);  Baz         var arr1=["foo", "Bar";           arr1["3"]= "Baz";       Console.log (arr1.length);  4       Console.log (arr1[3]);     Baz

PS: Because the array itself is an object, you add a member of the object by arr[' name ' or arr.name, instead of adding a member to the array. The array is only able to add or access the members of the array only through Arr[num] and num is the natural number .

Property Descriptor: Available through Object.defineproperty (..) To add a new property or modify an existing attribute and set the property.

var myobj={};object.defineproperty (MYOBJ, "a", {  value:2,  writeable:true,configurable:true,enumerable: true}); myobj.a;  2

Invariance: The immutable nature of attributes or objects can be implemented in a number of ways. All methods create shallow invariance, that is, they affect only the target object and its immediate properties.

(1) Object constants, writable and configurable are set to false. Cannot be modified, redefined, or deleted

(2) Prohibition of expansion, object.preventextensions (MYOBJ);

(3) Sealing, Object.seal (..) Creates a sealed object that actually calls Object.preventextensions (..) on an existing object. And mark all existing properties as configurable to false. You cannot add new properties after sealing, and you cannot reconfigure or delete any existing properties to modify the property values.

(4) Obj.preventextensions () () {}) frozen, Object.freeze (..) Creates a frozen object that actually calls Object.seal on an existing object (..) And mark all data access properties as writable to false. Prevents modifications to the object itself and any of its immediate properties.

Deep Freeze method: Call Object.freeze (..) on the object first, then iterate through all the objects it references and invoke Object.freeze on those objects (..) Depth depth

[[get]] Get property value [[PUT]] Set property value

A get operation is triggered when a property of an object is referenced, and a put operation is triggered when an object property is set.

Traverse:

The for...in loop can be used to iterate through an enumerable list of properties of an object and to point to a value by traversing the subscript.

ForEach (...) Iterates through all the values in the array and ignores the return value of the callback function

Every (...) will run until the callback function returns FALSE.

Some (...) will run until the callback function returns TRUE.

For...of first requests an iterator object to the object being accessed, and then iterates through all the values through the next () method of the Iterator object.

var myarr=[1,2,3];for (Var V of Myarr) {  console.log (v);}

var myarr=[1,2,3];var it=myarr[symbol.iterator] (); It.next ();                 {value:1, Done:false}it.next ();                 {value:2, Done:false}it.next ();       {value:3, Done:false}it.next ();      {Done:true}

Use Symbol.iterator in ES6 to get the @ @iterator internal properties of an object. The @ @iterator itself is not an iterator object, but rather a function that returns an Iterator object. Value represents the current traversal value, and done means that there are also values that can be traversed. For...of Loop each time the next () method of the MyObj iterator object is called, the internal pointer moves forward and returns the next value of the object's property list.

4-Mixed Object "class"

5-Prototypes

JavaScript objects have a special prototype built-in property, which is essentially a reference to other objects.

[[Prototype]] mechanism refers to an internal link in an object that references another object. Its essence is the association between objects. If the desired property or method reference is not found on the first object, the engine will continue to look on the object associated with [[Prototype]], and if the latter is not found, continue looking for the latter's [[Prototype]] until Object.prototype is found or reached. The link to this series of objects is called the prototype chain. All normal objects have built-in object.prototype that point to the top of the prototype chain.

The most common way to associate two objects is to use the New keyword for function calls. When you invoke a function using new, the. Prototype property of the new object is associated to another object. A function call with new is often called a constructor call.

A prototype is essentially an object in which other objects can implement property inheritance. All objects have a prototype by default. Multiple instances share a common prototype. Once a prototype attribute is defined, it can be inherited by multiple instances that reference it.

Prototype is a property of a constructor that points to an object, which acts as a base reference for all instances created by the constructor, and can think of the object's base reference as an automatically created hidden property that, when accessing a property of an object, finds the object itself, finds it, and returns if no , the property of the object to which the base reference points is found, so that it looks up along the prototype chain until it finds or reaches the root.

Prototype chain: An object chain consisting of objects used to inherit and share attributes. Make the prototype object equal to an instance of another constructor, so that the prototype object will contain a pointer to another prototype. Correspondingly, another prototype contains pointers to another constructor. If another prototype is another instance of the constructor, the layers are progressive, forming the chain between the instance and the prototype, that is, the prototype chain.

In a nutshell, each object and prototype has a prototype, and the object's prototype points to the parent of the object, and the parent's prototype points to the parent's parent, which is called the prototype chain through the layers of the stereotype. An instance of an object as a prototype of another object.

The function has a prototype property that points to the prototype object of the function, which contains the shared properties and methods of the instance created by the function, that is, the properties and methods of the prototype object are shared by all instances. This prototype object has a constructor property that points to the constructor. Each object created through the constructor contains an internal pointer to the prototype object _proto_

JavaScript objects are created by constructors, and each object has a constructor property that represents the constructor of the object. The prototype of all instances refers to the stereotype properties of the constructor.

6-Behavior Delegation

。。。。。。

I think I'm going to get dizzy with the "class" I'm talking about, isn't there a class in JavaScript? Small AH small Ah young rookie, you want to run faster yo, not, to fly up yo, then can fly high ...

You don't know, javascript-. Book notes

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.