Do not know the JavaScript

Source: Internet
Author: User
Tags access properties event listener

Objective

You don ' t know JavaScript is the previous series of GitHub articles

At the beginning of this title, I feel how the foreigner also engaged in the title of the party, with this conflict of relatively strong topic to attract attention, so that initially really did not go to see the content. Until out of the Chinese version of "You do not know the JavaScript", a look at the evaluation of everyone agreed, bought a read, the content is really good, a lot of places, let me this halfway switch JavaScript people suddenly enlightened. The Chinese version is now rolled up, the volume should be rolled out soon, the next volume will wait a little longer

What are scope and closure scopes

1. Modern JavaScript is no longer interpreted and executed but compiled. However, unlike the traditional compilation language, it is not compiled in advance and the results of the compilation cannot be ported. During the compilation process, there are three phases of word breaker/lexical analysis , parsing/syntax analysis , and code generation .

2. take var a = 2; As an example, the processing of this program statement requires the cooperation of the engine , compiler and scope . The engine is responsible for the compilation and execution of the entire JavaScript program from beginning to end, the compiler is responsible for parsing and code generation, and the scope is responsible for collecting and maintaining a series of queries consisting of all declared identifiers and implementing a set of rules To determine which code is currently executing to access these identifiers.

3. for var a = 2; the compiler first looks for a variable with that name in the scope, and then executes the compiler-generated code in the engine, looking for the scope first. Performs an assignment if it is found, or throws an exception

4. There are two types of engine-to-variable lookups:LHS queries and RHS queries . When the variable appears to the left of the assignment operation is a LHS query, the right side of the occurrence is the RHS query

Lexical scopes

1. Lexical scopes are scopes defined in the lexical phase. Lexical scopes are determined by where you write the variables and block scopes when you write the code, and the lexical processor maintains scope when parsing code

    1. function foo (a) {     var b = A * 2;     function Bar (c) {         console.log (a,b,c);     }     Bar (b * 3); } foo (2);     
      This example has a level three nested scope
    2. Scope Lookup stops when a first matching identifier is found
    3. Eval and with can spoof lexical scopes, not recommended
function scope and block scope
    1. JavaScript has a function-based scope, and the variables that belong to this function can be used and reused throughout the scope of the function.
    2. (function fun(){})() 
      The difference between a function expression and a function declaration is to see where the function keyword appears in the declaration. If the function is the first word in the declaration, then it is a functional declaration, otherwise it is a function expression
    3. With,try/catch has block scope, easy to use the implementation of block-level scope is ES6 bring the Let keyword
Improve

1. The following example

The above code output is not undefined, but 2. Because the above code needs to be compiled by the compiler, the compiler will first make a variable declaration, and then by the engine for variable assignment, so the above variable declaration is written in the second row, but the declaration process is first executed

    1. The above code is not a throw referenceerror exception, but an output undefined
    2. Only declarations will be promoted, assignments and other operational logic will remain in place
    3. Foo (); function foo () {     console.log (a);//undefined     var a = 2;}
      Foo ();//Not Referenceerror, is typeerror var foo = function bar () {}; Foo is promoted and assigned to the scope, so Foo () does not cause referenceerror, but Foo is not assigned a function call to undefined, so it throws TypeError
Scoped closures
    1. The internal function is passed outside the lexical scope, and it will hold the drink for the original definition scope, regardless of where it executes the function will use closures
    2. Essentially, whenever and wherever a function is treated as a first-level value type and passed around, you see the closure's application in these functions. In a timer, event listener, Ajax request, web workers, or any other asynchronous task, as long as the callback function is used, the closure is actually used
    3. The encapsulation of the module takes advantage of closures, hides internal variables, and returns an object of a public API, a returned object that forms a closed-packet access to the private variables of the module.
Dynamic scopes

1. Lexical scopes are rules for how a set of engines can find variables and where to find them. The most important characteristic of lexical scopes is the writing phase of code in the process of its definition.

2. The dynamic scope makes the scope a form that is dynamically determined at run time, rather than statically determined when writing code.

function foo () {     console.log (a);//2} function Bar () {     var a = 3;     

The lexical scope allows a in Foo () to be referenced by RHS to a in the global scope, so output 2; Dynamic scopes do not care about how functions and scopes are declared and where they are declared, only about where they are called. In other words, the scope chain is based on the call stack, not the scope nesting in the code. If you look at the dynamic scope, the above code will output 3 when executed

3.JavaScript does not have a dynamic scope, but it is somewhat like a dynamic scope in this mechanism, and this is concerned with how the function is called.

This lexical
  1. ES6 uses the arrow function to associate this with the lexical scope.
  2. If you encounter this loss before, the common method is to replace this reference with a local variable
    var obj = {     msg: ' Awesome ',     cool:function () {         setTimeout (function timer () {             console.log (this.msg);             } , ();             }     }; var msg = ' not awesome '; Obj.cool (); Not awesome var obj = {     msg: ' Awesome ',     cool:function () {     var = this; SetTimeout (function timer (        Console.log (self.msg);         },100);     }  ; var msg = ' not awesome '; Obj.cool (); Awesome var obj = {     msg: ' Awesome ',     cool:function () {setTimeout () = {         Console.log (this.msg);         },100);     } }; var msg = ' not awesome '; Obj.cool (); Awesome var obj = {     msg: ' Awesome ',     cool:function () {         setTimeout (function timer () {             Console.log ( THIS.MSG); }.bind (This), ();             }     }; var msg = ' not awesome '; Obj.cool (); Awesome            
This and object prototypes this comprehensive parsing
    1. The default binding.
      function foo () {     console.log (THIS.A);} var a = 2; foo ();//2
      In the example above, the function call has a default binding applied, which points to the global object
    2. Implicit binding. Whether the call location has a context object, or whether it is owned or contained by an object.
      function foo () {     console.log (THIS.A);} var obj={     a:2,     
      When Foo () is called, the foothold points to the Obj object. When a function reference has a context object, the implicit object binds the this in the function call to the context object.
    3. Displays bindings. Show bindings using Apply,call or Bind
    4. New binding.
      • The constructors in JavaScript are just some of the functions that are called when the new operator is used. They do not belong to a class, nor do they instantiate a class. In fact, they are not even a special type of function, they are just normal functions called by the new operator.
      • Using new to invoke a function, or a constructor call, will automatically do the following: a) Create a completely new object B) This new object will be executed [[prototype]] connection C) This new object will be bound to the function call this d) if the function does not return other objects, Then the function call in the new expression will automatically return the object
    5. Priority level. New binding > Show Bindings > Implicit binding > Default Bindings
Object
  1. Property descriptor
    var obj = {}; Object.defineproperty (    obj,    "a",    {         value:2,         writable:true,         configurable:true,         Enumerable:true     }); OBJ.A;//2    
    • Writable determines whether the value of the property can be modified, and when writable is false, changes to obj.a silently fail.
    • Configurable indicates whether the property can be configured, and if False, and then calls DefineProperty for obj to modify the settings, it throws TypeError
    • Enumerable indicates whether the property appears in the object enumeration property and, if False, does not appear in the for...in loop
  2. The object constant. Combined with Writable:false and configurable:false you can create a true constant attribute (non-modifiable, non-redefined, non-deleted)
  3. Prohibit expansion. You can use the Object.preventextensions () method if you want to suppress the addition of new properties to an object and preserve existing properties
  4. Seal. Object.seal () Creates a sealed object that actually calls the Object.preventextensions () method on an existing object and marks all the properties as Configurable:false
  5. Frozen. Object.freeze () Creates a frozen object that invokes the Object.seal () method on an existing object and marks all data-access properties as Writable:false
  6. [[Get]],[[put]].
    • var obj = {     This._a_ = 2;     Get A () {return this._a_;},     set a (val) {This._a_ = Val * 2;}}; Object.defineproperty (     obj,     "B",     {         get:function () {return this._a_ * 2},         enumerable:true     } )
Prototype

This section is to think that the book is a bit around, not clear. Recommended Reading

    1. Constructor, prototype, Proto detailed
    2. The relationship between Proto and prototype in JavaScript
    3. How does proto differ from Constructor.prototype?
    4. Understanding JavaScript Object-oriented thinking
Behavior Delegation
    1. [[prototype]] mechanism is an internal link in an object that references another object if a required property or method reference is not found on the first object, the engine will continue to find on the object associated with [[Prototyoe]]. Similarly, if the latter does not find the required reference, it will continue to look for its [[prototype]], and so on, this series of objects linked to the prototype chain. In other words, this mechanism is the association between objects.
    2. [[prototype]] is a design pattern that differs from a class, and is a design pattern for delegate behavior.

Do not know the JavaScript

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.