JS code Pre-parsing principle, function-related, object-oriented

Source: Internet
Author: User
Tags parse error script tag variable scope

JS important points of knowledge

Here is a list of some JS important points of knowledge (not comprehensive, but you feel very important). Thoroughly understand and master these knowledge points, for every friend who want to learn JS in depth should be necessary.

To explain or sample code with the form of comments, here is a small directory:

JS code Pre-parsing principle (including three paragraphs);

function correlation (including function parameter, call mode with parametric function, closure);

Object-oriented (including object creation, prototype chain, data type detection, inheritance).

JS code Pre-parsing principle

/****************** JS Code Pre-parsing principle ******************/
/*
JS code Pre-parsing, variable scope, scope chain, etc. should be able to learn the JS language as a prerequisite for knowledge.
Here are some brief explanations and some typical code snippets, to learn more, to find more relevant examples from the Web.

An explanation of the "JS execution sequence" is quoted on the Internet:
If a document flow contains more than one script snippet (the JS code delimited by the script tag or the introduced JS file), they run in the following order:
Step 1. Read the first code snippet (the JS execution engine does not execute the program one line at a time, but analyzes the execution in a paragraph)
Step 2. Do grammatical analysis, error report syntax errors (such as parentheses mismatch, etc.), and jump to step 5
Step 3. "Pre-parsing" of var variables and function definitions (never error, because only correct declarations are parsed)
Step 4. Execute code snippet with error (e.g. variable undefined)
Step 5. If there is a next code snippet, read the next code snippet and repeat steps 2
Step 6. End
*/
The following is a typical example of a code that gives three paragraphs:
/**********: A few basic statements **********/
alert (num); Undefined
var num = 0;
alert (str); Error: STR not defined
str = "string";
Alert (func); Undefined
var func = function () {alert (' exec func ');}
Test (); EXEC test
Alert (test ()); First exec test after undefined
function test () {alert (' exec test ');}

/********** Two: 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 the front var mark = 1; return 1

/********** Three: Include the second paragraph in the statement block **********/
When conditional (the code is contained in a conditional statement block)
if (false) {
var mark1 = 1;
function Mark1 () {
Alert ("exec mark1");
}
var Mark1;
alert (MARK1);
}
alert (MARK1);
Mark1 ();
Because parsing browser parsing is different, this code in different browsers to perform inconsistent results, specific reasons can be found on the internet answer

function correlation (including function parameter, call mode with parametric function, closure)

/****************** function-related ******************/

/**********: Function pass-through parameter **********/
/*
The programming language probably has the difference between the value type and the reference type, JS is no exception.
Primitive type: Undefined null number Boolean is a value type.
String is special because it is immutable, and the method defined by the string class cannot alter the contents of the string.
The function object array is a reference type for these three types.
*/
/* When a JavaScript function passes a parameter, it is a value pass.

In ECMAScript, the parameters of all functions are passed by value.
The delivery of the base type value is consistent with the basic type variable (using a new value in the stack),
The passing of the reference type value and the replication of the reference type variable are consistent (a pointer is stored in the stack, pointing to the same object in the heap).
Specific reference: http://www.xiaoxiaozi.com/2010/03/05/1719/
*/
function SetName (obj) {
Obj copies the value of person (the person is the reference address of an object), so obj also points to the object to which the person points.
Obj.name = "Xiaoxiaozi";
obj = {}; Have obj point to another object
Obj.name = "admin";
}
var person = {};
SetName (person);
alert (person.name); Xiaoxiaozi


/********** Two: Call mode with parameter function **********/
/* In different versions of DOM, the function is not called the same way. The standard recommended is AddEventListener and attachevent.
There is a lot of information to be found in both of these ways. But some of the deprecated function calls still have a practical application, and the data are not much found.
Here we mainly discuss how these functions are called
*/
var g = "global variable";
function Show (str) {
Alert ("My Site:" + str);
}
SetTimeout ("Show (g);", 100); G is a global variable and the function executes correctly
function T () {
var url = "www.xujiwei.cn";
var num = 2;
SetTimeout ("Alert (" +url+ ")", 3000); Parse error, www not defined
SetTimeout ("Alert (" +num+ ")", 3000); Correct analysis, pay attention to the comparison with the above sentence
SetTimeout ("Show (' url ');", 2000); Url
SetTimeout ("Show (" + URL + ");", 2000); Parse error, www not defined
SetTimeout ("Show (URL);", 2000); Parse error, URL not defined
SetTimeout (' "Show (" + URL + ");" ', 2000); Parse error, URL not defined
SetTimeout ("Show ('" + URL + "');", 2000); That's right
SetTimeout (function () {Show (URL);},1000); That's right
}
T ();
/* Conclusion:
such as onclick= "XX ();" When the function is called, the content inside the double quotation marks is parsed directly into the JS statement execution.
If the function is called with parameters, pay attention to compare the above various ways, and ensure that the parameters passed in are correct.
*/


/********** Three: Closure package **********/
/*
Closures, almost every learning JS friends have to discuss the issue, so a variety of relevant information.
It has a great role, but there are drawbacks, such as improper use, prone to memory leaks and other issues, so many people
Promote the use of less closures.

A classic application of closures is listed here, a controversial application.
*/
function Test1 () {//through closures, each time a different J value can be passed in.
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 function immediately, can one file have only one? Write the upper function as an immediate execution problem, what's going on?

/* This issue appears in the forum, there are many controversies
It is said that the new function dynamically generates a closed-packet structure, so the external variables can be saved.
There's nothing to say about closures, new function, which defines a function,
The value of I is also cured in its interior as a parameter of the new function.
*/

Object-oriented (including object creation, prototype chain, data type detection, inheritance)

/****************** Object-oriented ******************/

/**********: Object creation, prototype chain **********/
/* Discuss constructors (class mode) to create objects, and it is important to understand them in depth.
*/
function MyFunc () {}; Define an empty function
var anobj = new MyFunc (); With the new operator, an object is created with the Myfun function
Equivalent to:
function MyFunc () {};
var anobj = {}; Create an Object
anobj.__proto__ = Myfunc.prototype;
Myfunc.call (Anobj); Call the Anobj object as the this pointer myfunc function
/*
The process of creating an object with var anobject = new Afunction () can actually be divided into three steps:
First step: Establish a new object (AnObject);
The second step: Set the object's built-in prototype object (__PROTO__) to the prototype object referenced by the constructor prototype;
Step Three: Call the constructor as the This parameter, complete the initialization of the member settings, and so on.

After an object is established, any access and operations on the object are related only to the object itself and the string of objects on its prototype chain.
It's no longer related to the constructor.
In other words, the constructor simply introduces the prototype object and initializes the object two functions when the object is created.

Prototype chain: (Reference: http://hi.baidu.com/fegro/blog/item/41ec7ca70cdb98e59152eed0.html)
Each object, where the object should only refer to object enclosed in curly braces, does not include function, array. Pending verification? )
Will initialize a property within it, that is, __proto__, when we access the properties of an object,
If this property does not exist inside this object, then he will go to __proto__ for this attribute,
This __proto__ will have their own __proto__, so have been looking down, which is what we usually call the concept of the prototype chain.
*/

/* Understanding the principle of object creation, you can try to analyze the results of the bottom two examples */
var yx01 = new function () {return ' center '};
alert (YX01); [Object Object]
var yx02 = new function () {return new String ("Center")};
alert (yx02); Center
/* Explanation:
The "center point" is the basic string type, and the new string ("center") creates a string object.
As soon as the constructor after the new expression returns a reference object (array, object, function, and so on), the object created by the new is overwritten.
If you return an original type (no return is actually a return primitive type undefined),
Then it returns the object created by new.
Reference: http://www.planabc.net/2008/02/20/javascript_new_function/
*/



/********** II: Detection of data types **********/
/* Determine what the data type might think:
Constructor, typeof, Instanceof, Object.prototype.toString.call ()
*/
/***** 1, through the constructor property *****/
var myvar= new Array ("A", "B", "C", "D");
function A () {}
Myvar.constructor = A;
var c = myvar.constructor;
alert (c); function A () {}
It can be seen that the method of obtaining a type through the constructor property is easily modified and should not be used to determine the type.

/***** 2, through typeof *****/
/*
typeof is an operator, not a function.
The practical application of typeof is to detect whether an object has been defined or has been assigned a value.
such as if (typeof a!= "undefined") {}, do not use if (a) because if a does not exist (not declared) then an error occurs.
typeof generally only returns the following results when detecting object types:
number,boolean,string,function,object,undefined.
For Array,null, custom objects, and so on, use TypeOf to return object,
This is precisely the limitation of TypeOf.
*/
var num = new number (1);
var arr = [n/a];
Alert (typeof num); object, not number
Alert (typeof arr); Object instead of array
Alert (typeof null); Object

/***** 3, through instanceof *****/
/* Use the instanceof operator to determine whether an object is an instance of a class.
If obj instanceof class returns True, then the prototype of class is the same object as a prototype on the OBJ prototype chain.
That is, obj is either created by class or by a subclass of class.
*/
function T () {};
T.prototype = Array.prototype;
T.prototype = [];
var x = new T ();
Alert (x instanceof T);//Popup True
Alert (x instanceof Array);//Popup True
Alert (x instanceof Object);//Popup True
/*
It can be concluded that data types are not reliably judged by instanceof.
Because the prototype chain of an object (here X) can be very long, the type of each prototype can be different.

It is also prone to errors within the IFRAME:
That is, a page defines an array A, the page is nested an IFRAME, in the IFRAME through the Top.a instanceof array, is returned false.
This indicates that the parent page and the object in the embedded iframe are different and cannot be mixed together.
Change to Top.a instanceof top. Array will return True
*/

/***** 4, through Object.prototype.toString.call () *****/
/*
The Object.prototype.toString.call () function is:
1. Gets the class name (object type) of the object.
2. Then combine [object, get class name] and return.
Can be used to determine array,date,function and other types of objects
*/
var num = new number (1);
var arr = [n/a];
Alert (Object.prototype.toString.call (num)); [Object number]
Alert (Object.prototype.toString.call (arr)); [Object Array]

Example extension: (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 A () {}
Window.utils.isFunction (A); True
Window.utils.isObject (New A ()); True
Window.utils.isArray ([]); True

/*
The framework of jquery is to use this method to judge the type of object, so this method can be used as the authoritative judgment method.
However, if you override the Object.prototype.toString method, you can then use it to determine if the data type is wrong.
Therefore, generally do not rewrite the Object.prototype.toString method.
*/




/********** Three: Inheriting **********/
/*
JS inheritance and closures, almost every friend who want to learn JS in-depth discussion of the problem, so all kinds of relevant information.
JS inherited code version is very many, but the principle is the same, the core is the use of prototype objects.
In order to be similar to other object-oriented language styles, most of them use "class style" style simulation.

The detailed principles of inheritance are no longer mentioned, there are many information on the Internet.
Here's an example: the inheritance written by jquery author John Resig.
(where the detailed comments are from a blog, do not know who is original, here privately reprint out)
*/
(function () {
The initializing variable is used to indicate whether the class is currently in the creation phase,
-The prototype method Init cannot be called during the creation phase of the class
-We have elaborated this issue in the third article of this series
Fntest is a regular expression, possibly with a value of (/\b_super\b/or/.*/)
-The test for/xyz/.test (function () {xyz;}) is to detect if the browser supports the test parameter as a function
-but I tested the ie7.0,chrome2.0,ff3.5 and this test returns TRUE.
-So I think this is true for most of the fntest assignment: Fntest =/\b_super\b/;
var initializing = false, Fntest =/xyz/.test (function () {xyz;})? /\b_super\b/:/.*/;
Base class constructors
This is the window, so this whole code opens up a window to the outside-window. Class
This. Class = function () {};
Inheritance method definition
Class.extend = function (prop) {
This place is very confusing, remember what I mentioned in the second article in this series?
-This refers to what is not defined, but depends on how the function is called.
-we already know that extend is definitely called as a method, not as a constructor
-So here this is not the object, but the function (that is, the class), then 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 following code
var _super = This.prototype;
Inheritance is accomplished by pointing the stereotype of a subclass 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's very stiff to read, and I'll 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, and the 91st line of the comment code is illustrative.
This._super = _super[name];
var ret = fn.apply (this, arguments);
This._super = tmp;
return ret;
};
}) (name, Prop[name]):
Prop[name];
}
This place can be seen, Resig is very camouflage OH
-Use a local variable with the same name to overwrite the global variable, it's confusing.
-If you feel a mouthful, you can use another name, such as function F () instead of function Class ()
-Note: The class here is not the base class constructor defined at the outermost layer
The class here is not the same as the Window.class function on the top, here is the function local variable inside the Window.class
function Class () {
When instantiating a class, call the prototype method init
if (!initializing && this.init)
This.init.apply (this, arguments);
}
The prototype of the subclass points to the instance of the parent class (the key to complete the inheritance)
Class.prototype = prototype; Class refers to the upper class, not the first window. Class
Fix constructor pointing error
Can I use Class.prototype.constructor = Class to fix???
Class.constructor = Class;
The subclass automatically gets the Extend method, Arguments.callee points to the function that is currently executing
Class.extend = Arguments.callee;
return Class;
};
})();

JS code Pre-parsing principle, function-related, object-oriented

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.