Summary of important JS knowledge points

Source: Internet
Author: User

The example code is followed by a comment. Here is a small directory:
JS Code pre-parsing principle (including three paragraphs );
Function-related (including function passing parameters, call methods with parameter functions, closures );
Object-oriented (including object creation, prototype chain, data type detection, inheritance ).
JS Code pre-parsing Principle
Copy codeThe Code is as follows:
/***************** JS Code pre-Resolution Principle **************** **/
JS Code pre-parsing, variable scope, and scope chain should be essential for learning JS language.
Below are some brief explanations and some typical code segments. To learn more, you can search for more examples from the Internet.
Reference an online explanation of "execution sequence of JS:
If a document stream contains multiple script code segments (JavaScript code separated by script tags or imported js files), the running sequence is:
Step 1. Read the first code segment (the js execution engine does not execute the program in one row, but analyzes and executes the program in one row)
Step 2. Perform syntax analysis. If there is a mistake, a syntax error is reported (for example, parentheses do not match), and jump to Step 5.
Step 3. Perform "pre-resolution" on var variables and function definitions (no error will be reported because only the correct declaration is parsed)
Step 4. Execute the code segment. If there is an error, an error is returned (for example, the variable is undefined)
Step 5. If there is another code segment, read the next code segment and repeat Step 2.
Step 6. End
// Below are three typical code examples:
/********** 1: several basic statements **********/
Alert (num); // undefined
Var num = 0;
Alert (str); // error: str undefined
Str = "string ";
Alert (func); // undefined
Var func = function () {alert ('exec func ');}
Test (); // exec test
Alert (test (); // first exec test and then undefined
Function test () {alert ('exec test ');}
/********* 2: The function name is the same as the variable name **********/
// Var mark = 1;
Function mark (x ){
Return x * 2;
Var mark;
Alert (mark); // function mark (x) {return x * 2 ;}
// Remove var mark = 1 from the front. 1 is returned.
/********** 3: Include the second paragraph in the statement block **********/
// When conditions exist (the code is included in the Condition Statement block)
If (false ){
Var mark1 = 1;
Function mark1 (){
Alert ("exec mark1 ");
// Var mark1;
Alert (mark1 );
Alert (mark1 );
Mark1 ();
// The results of the Code executed in different browsers vary depending on the resolution of the browser. You can find the answer from the Internet for specific reasons.

Function-related (including function passing parameters, call methods with parameter functions, closures)
Copy codeThe Code is as follows:
/********** 1: function parameter passing **********/
Programming Languages generally have differences between value types and reference types, and JS is no exception.
Original Type: undefined null number boolean is a value type.
String is special because it cannot be changed. The String content cannot be changed in the methods defined by the string class.
Function object array is of reference type.
/* When a JavaScript function passes a parameter, it is a value transfer.
In ECMAScript, all function parameters are passed by value.
The transfer of the basic type value is consistent with the replication of the basic type variable (using the new value in the stack ),
The transfer of reference type values is the same as that of reference type variables (the stack memory is a pointer pointing to the same object in the heap ).
Function setName (obj ){
// Obj copies the value of person (person is the reference address of an object), so obj also points to the object pointed to by person.
Obj. name = "xiaoxiaozi ";
Obj = {}; // point obj to another object
Obj. name = "admin ";
Var person = {};
SetName (person );
Alert (person. name); // xiaoxiaozi
/********** 2: Call method with parameter functions **********/
/* In different DOM versions, function calling methods are not the same. AddEventListener and attachEvent are recommended.
The two methods have a lot of information to query. However, some function calls that are no longer recommended still have practical applications, and there are not many materials found.
The call methods of these functions are discussed here.
Var g = "global variable ";
Function show (str ){
Alert ("my site:" + str );
SetTimeout ("show (g);", 100); // g is a global variable and the function is correctly executed.
Function t (){
Var url = " ";
Var num = 2;
// SetTimeout ("alert (" + url + ")", 3000); // resolution error, www undefined
// SetTimeout ("alert (" + num + ")", 3000); // The parsing is correct. Pay attention to the comparison with the previous sentence.
// SetTimeout ("show ('url');", 2000); // url
// SetTimeout ("show (" + url + ");", 2000); // resolution error, www undefined
// SetTimeout ("show (url);", 2000); // resolution error, url undefined
// SetTimeout ('"show (" + url + ");"', 2000); // resolution error, url undefined
// SetTimeout ("show ('" + url + "');", 2000); // correct
// SetTimeout (function () {show (url) ;}, 1000); // correct
T ();
/* Conclusion:
Such as onclick = "xx ();" and other function call methods, the content in the double quotation marks is directly parsed as js statement execution.
If the called function has parameters, compare the preceding methods to ensure that the parameters passed in are correct.
/********** 3: Closure **********/
Closures are a question that almost everyone who learns JavaScript will discuss. Therefore, there are all kinds of related materials.
It has a great role, but it also has drawbacks. For example, improper use may easily cause memory leakage and other problems, so many people
We recommend using less closures.
Here we list a classic application of closures, a controversial application.
Function test1 () {// You can input different j values each time through the closure.
For (var j = 0; j <3; j ++ ){
(Function (j ){
SetTimeout (function () {alert (j)}, 3000 );
}) (J );
Test1 ();
/* This is a typical application of closures */
(Function tt (){
For (var I = 1; I <4; I ++ ){
Document. getElementById ("B" + I). attachEvent ("onclick ",
New Function ('alert ("This is button '+ I +'"); '); // test in IE
}) () // Execute the function immediately. Can only one file exist? I wrote the above function as an immediate execution problem. Why?
/* There are a lot of controversies when this problem occurs in the Forum
It is said that the new Function dynamically generates a closure structure Function, so it can save external variables.
It is irrelevant to the closure. The new Function is a newly defined function,
The I value is also solidified in the new function as a parameter.

Object-oriented (including object creation, prototype chain, data type detection, inheritance)
Copy codeThe Code is as follows:
/****************** Object-oriented ******************/
/********** 1: Object creation and prototype chain **********/
/* It is very important to discuss how Constructors (class methods) create objects and understand these content in depth.
Function MyFunc () {}; // defines an empty function
Var anObj = new MyFunc (); // use the new operator and use the MyFun function to create an object.
// Equivalent:
Function MyFunc (){};
Var anObj ={}; // create an object
AnObj. _ proto _ = MyFunc. prototype;
MyFunc. call (anObj); // use the anObj object as the this pointer to call the MyFunc function.
The process of creating an object in the form of var anObject = new aFunction () can be divided into three steps:
Step 1: Create a new object (anObject );
Step 2: Set the built-in prototype object (_ proto _) of this object to the prototype object referenced by the constructor prototype;
Step 3: Use this object as the this parameter to call the constructor and complete initialization such as member settings.
After an object is created, any access and operations on the object are only related to the object itself and the objects on its prototype chain,
It is no longer related to the constructor.
In other words, constructor only introduces the prototype object and initialization object when creating an object.
Prototype chain: (reference:
Each object (here the object should only refer to the object enclosed in braces, excluding function and array. To be verified ?)
Will Initialize an attribute inside it, that is, _ proto __. when we access the attribute of an object,
If this attribute does not exist in the object, it will be searched for in _ proto,
The _ proto _ has its own _ proto __, so we keep looking for it, that is, the concept of prototype chain that we usually call.
/* Understand the principle of object creation, and try to analyze the results of the following two examples */
Var yx01 = new function () {return "center "};
Alert (yx01); // [object Object]
Var yx02 = new function () {return new String ("center ")};
Alert (yx02); // "center"
/* Explanation:
"Circle Center" is a basic String type, while new string ("Circle Center") creates a String object.
As long as the constructor after the new expression returns a reference object (array, object, function, etc.), it will overwrite the newly created object,
If an original type is returned (undefined is the original type of return when no return is returned ),
Then, the new object is returned.
/********** 2: Data Type detection **********/
/* Possible methods to determine the Data Type:
Constructor, typeof, instanceof, Object. prototype. toString. call ()
/***** 1. Use the constructor attribute *****/
Var myvar = new Array ("a", "B", "c", "d ");
Function (){}
Myvar. constructor =;
Var c = myvar. constructor;
Alert (c); // function (){}
// It can be seen that the method for obtaining the type through the constructor attribute is easy to modify and should not be used to determine the type.
/***** 2. Use typeof *****/
Typeof is an operator rather than a function.
The actual application of typeof is to check whether an object has been defined or assigned a value.
For example, if (typeof! = "Undefined") {}, instead of using if (a) because if a does not exist (not declared), an error occurs.
When typeof detects object types, only the following results can be returned:
Number, boolean, string, function, object, undefined.
If typeof is used for Array, Null, and custom objects, all objects are returned,
This is the limitation of typeof.
Var num = new Number (1 );
Var arr = [1, 2, 3];
Alert (typeof num); // object instead of number
Alert (typeof arr); // object instead of Array
Alert (typeof null); // object
/***** 3. Use instanceof *****/
/* Use the instanceof operator to determine whether the object is an instance of a class.
If obj instanceof Class returns true, the Class prototype is the same object as a prototype in the obj prototype chain,
That is, obj is created either by Class or by a subclass of Class.
Function t (){};
T. prototype = Array. prototype;
// T. prototype = [];
Var x = new t ();
Alert (x instanceof t); // true is displayed.
Alert (x instanceof Array); // true is displayed.
Alert (x instanceof Object); // true is displayed.
It can be seen that the data type is not reliable through instanceof.
Because the prototype chain of an object (here x) can be very long, and the type of each prototype can be different.
In addition, the iframe may also cause errors:
There is a page that defines an Array a, and the page is nested with an IFrame. In the Iframe, through top. a instanceof Array, false is returned.
This indicates that the objects in the parent page and embedded iframe are different and cannot be used together.
Change top. a instanceof top. Array to true.
/***** 4. Use Object. prototype. toString. call ()*****/
Object. prototype. toString. call:
1. Get the class name (Object Type) of the object ).
2. Combine the [object, obtained class name] and return the result.
It can be used to determine objects of the Array, Date, Function, and other types.
Var num = new Number (1 );
Var arr = [1, 2, 3];
Alert (Object. prototype. toString. call (num); // [object Number]
Alert (Object. prototype. toString. call (arr); // [object Array]
// Extension example: (apply is equivalent to call)
Window. utils = {
ToString: Object. prototype. toString,
IsObject: function (obj ){
Return this. toString. apply (obj) ===' [object Object] ';
IsFunction: function (obj ){
Return this. toString. apply (obj) ===' [object Function] ';
IsArray: function (obj ){
Return this. toString. apply (obj) ===' [object Array] ';
Function (){}
Window. utils. isFunction (A); // true
Window. utils. isObject (new A (); // true
Window. utils. isArray ([]); // true
JQuery and other frameworks use this method to determine the object type. Therefore, this method can be used as an authoritative method.
However, if the Object. prototype. toString method is rewritten, an error may occur when it is used to determine the data type,
Therefore, do not overwrite the Object. prototype. toString method.
/********** 3: Inherit **********/
Similar to closures, JS inheritance is a question that almost everyone who wants to learn about JS needs to discuss. Therefore, there are all kinds of related materials.
JS inherits a lot of code versions, but the principles are the same. The core is to use prototype objects.
To be similar to the style of other object-oriented languages, most of them adopt the "class style" style simulation.
The detailed principles of inheritance will not be described in detail. There are a lot of information on the Internet.
Here is an example of inheritance written by John Resig, the author of Jquery.
(The detailed comment is from a blog. I don't know who is the original one. I will post it here without permission)
(Function (){
// The initializing variable is used to indicate whether the current class is being created,
//-During the class creation stage, the original method init cannot be called.
//-We have elaborated on this issue in the third article in this series.
// FnTest is a regular expression. The possible value is/\ B _super \ B/or /.*/)
//-Test/xyz/. test (function () {xyz;}) to check whether the browser supports the function as the test parameter.
//-However, I tested IE7.0, Chrome2.0, and FF3.5. true is returned for all tests.
//-So I think it is also true to assign a value to fnTest in most cases: fnTest =/\ B _super \ B /;
Var initializing = false, fnTest =/xyz/. test (function () {xyz ;})? /\ B _super \ B /:/.*/;
// Base class Constructor
// This is a window, so the entire code Segment opens a window to the outside world-window. Class
This. Class = function (){};
// Inheritance Method Definition
Class. extend = function (prop ){
// This is a confusing place. Do you still remember what I mentioned in the second article in this series?
//-This is not defined, but depends on how the function is called.
//-We already know that extend must be called as a method instead of a constructor.
//-So here this points not to the Object, but to the Function (that is, the Class), so this. prototype is the prototype Object of the parent Class.
//-Note: _ super points to the prototype object of the parent class. We will encounter this variable multiple times in the subsequent code.
Var _ super = this. prototype;
// Inherit by pointing the subclass prototype to an instance object of the parent class
//-Note: this is a base Class Constructor (that is, Class)
Initializing = true;
Var prototype = new this ();
Initializing = false;
// I think this code has been optimized by the author, so it is very hard to read. I will explain it later.
For (var name in prop ){
Prototype [name] = typeof prop [name] = "function "&&
Typeof _ super [name] = "function" & fnTest. test (prop [name])?
(Function (name, fn ){
Return function (){
Var tmp = this. _ super; // this is necessary. You can describe the 91st-line annotation code.
This. _ super = _ super [name];
Var ret = fn. apply (this, arguments );
This. _ super = tmp;
Return ret;
}) (Name, prop [name]):
Prop [name];
// This area shows that Resig is a good disguise.
//-It is confusing to use a local variable with the same name to overwrite the global variable.
//-You can use another name, such as function F (), to replace function Class ()
//-Note: The Class here is not the base Class constructor defined in the outermost layer.
// The Class here is different from the window. Class function above. Here is the local variable of the function in window. Class.
Function Class (){
// Call the prototype method init during class instantiation
If (! Initializing & this. init)
This. init. apply (this, arguments );
// Prototype of the subclass points to the instance of the parent class (the key to inheritance)
Class. prototype = prototype; // Class refers to the above Class, not the start window. Class
// Fixed the constructor pointing error.
// Can Class. prototype. constructor = Class; be used for correction ???
Class. constructor = Class;
// Subclass automatically obtains the extend method. arguments. callee points to the currently executed function.
Class. extend = arguments. callee;
Return Class;

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: 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.