Explain or the example code with annotation form, here make a small directory:
JS code Pre-resolution principle (including three paragraphs);
function correlation (including function argument, call mode with parameter function, closure);
Object-oriented (including object creation, prototype chain, data type detection, inheritance).
JS code Pre-resolution principle
Copy Code code as follows:
/****************** JS Code Pre-resolution principle ******************/
/*
JS code Pre-resolution, variable scope, scope chain, etc. should be able to learn from the introduction of the JS language necessary knowledge.
Here are some brief explanations and some typical snippets, and to learn more, you can search for more relevant examples from the Web.
Refer to a section on the web about the "JS Order of Execution" explanation:
If a document flow contains multiple script snippets (JS code separated by a script label or a JS file that is introduced), they run in the following order:
Step 1. Read the first code snippet (the JS execution engine does not execute the program in one line, but a section of the execution)
Step 2. Do a grammar analysis, the error of the report syntax errors (such as parentheses do not match, etc.), and jump to step 5
Step 3. "Pre-resolution" for VAR variables and function definitions (never error, because only correct declarations are parsed)
Step 4. Execute code snippet, error errors (such as variable undefined)
Step 5. If you have the next code snippet, read the next code snippet, repeat step 2
Step 6. End
*/
Here's a three-paragraph code example that feels more typical:
/**********: A few basic sentences **********/
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 of var mark = 1; then return 1.
/********** Three: Include the second paragraph in the statement block **********/
When there is a condition (the code is included in the conditional statement block)
if (false) {
var mark1 = 1;
function Mark1 () {
Alert ("exec mark1");
}
var Mark1;
alert (MARK1);
}
alert (MARK1);
Mark1 ();
Because parsing browser resolution is different, the results of this code in different browsers are inconsistent, specific reasons to find answers from the internet
function correlation (including function arguments, call mode with parameter function, closure)
Copy Code code as follows:
/****************** function Related ******************/
/********** One: function parameter **********/
/*
The programming language probably has the difference between the value type and the reference type, JS is no exception.
Original 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 change the contents of the string.
The three types of function object array are reference types.
*/
/* The JavaScript function passes the parameter, is the value pass.
In ECMAScript, the parameters of all functions are passed by value.
The delivery of the base type value is consistent with the base type variable replication (using the new value in the stack),
The delivery of reference type values and the replication of reference type variables are consistent (the stack holds pointers, pointing to the same object in the heap).
Specific reference: http://www.xiaoxiaozi.com/2010/03/05/1719/
*/
function SetName (obj) {
obj copies the person's value (person is the reference address of an object), so obj also points to the object that person points to.
Obj.name = "Xiaoxiaozi";
obj = {}; Let 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, functions are called differently. Standard recommendation is AddEventListener and attachevent.
There is a lot of information to be found in these two ways. However, some of the functional calls that have not been recommended are still in use, and the relevant data are not found much.
This is mainly about how these function calls
*/
var g = "global variable";
function Show (str) {
Alert ("My Site:" + str);
}
SetTimeout ("Show (g);", 100); G is a global variable, 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); Parse correctly, pay attention to 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 ();" The function calls the way, in double quotation mark content directly resolves to the JS statement execution.
If you call the function with parameters, pay attention to the comparison of the above various methods to ensure that the parameters passed in the correct.
*/
/********** III: Closure **********/
/*
Closures, almost every learning JS friends have to discuss the issue, so all kinds of relevant information everything.
Its role is very large, but there are drawbacks, such as if the use of improper, easy to cause memory leaks and so on, so many people
promote less closures.
Here is a list of the classical applications of closures, a controversial application.
*/
function Test1 () {//through closures, each can pass a different J value.
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",
The new Function (' Alert (' The ' is button ' + i + '); Testing in IE
}
} ()///execute function immediately, can a file have only one? Write the top function as immediate execution problem, what's going on?
* * This issue appears in the forum, there are a lot of controversy
There is a function that the new function dynamically generates a closure structure, so it can save the external variables.
It's not about the closure, the new function, which defines a function,
The value of I is also used as the parameter of this new function to solidify in its interior.
*/
Object-oriented (including object creation, prototype chain, data type detection, inheritance)
Copy Code code as follows:
/****************** Object-oriented ******************/
/********** One: Object creation, prototype chain **********/
/* Discuss constructors (class) Create objects, it is important to understand these things in depth
*/
function MyFunc () {}; Define an empty function
var anobj = new MyFunc (); With the new operator, you create an object by using the Myfun function
Equivalent to:
function MyFunc () {};
var anobj = {}; Create an Object
anobj.__proto__ = Myfunc.prototype;
Myfunc.call (Anobj); Call the MyFunc function with the Anobj object as the this pointer
/*
The process of creating objects in the form of var anobject = new Afunction () can actually be divided into three steps:
The first step: to establish a new object (AnObject);
Step two: Set the Prototype object (__PROTO__) built into the object as 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 operation on the object is only relevant to the object itself and the string of objects on its prototype chain.
Has nothing to do with constructors.
In other words, the constructor only acts as an introduction to the prototype object and the initialization object in the creation of the object two.
Prototype chain: (Reference: http://hi.baidu.com/fegro/blog/item/41ec7ca70cdb98e59152eed0.html)
Each object, where the object should only refer to the object enclosed in braces, excluding function, array. Pending verification? )
Initializes an attribute within it, which is __proto__, when we access the properties of an object,
If this property does not exist inside the object, then he goes to the __proto__ to find the attribute,
This __proto__ will have its own __proto__, so keep looking for it, 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 two examples below * *
var yx01 = new function () {return "center"};
alert (YX01); [Object Object]
var yx02 = new function () {return new String ("Center")};
alert (yx02); Center
/* Explanation:
"Center" is the basic string type, and new string ("center") creates a string object.
Whenever the constructor after the new expression returns a reference object (array, object, function, and so on), the object created by new is overwritten.
If an original type is returned (the return primitive type is actually undefined),
Then you return the object created by new.
Reference: http://www.planabc.net/2008/02/20/javascript_new_function/
*/
/********** II: Detection of data types **********/
/* Determine the method that the data type may think of:
Constructor, typeof, Instanceof, Object.prototype.toString.call ()
*/
/***** 1, through constructor properties *****/
var myvar= new Array ("A", "B", "C", "D");
function A () {}
Myvar.constructor = A;
var c = myvar.constructor;
alert (c); function A () {}
It is obvious that the method of getting the 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 actual application of typeof is used to detect whether an object has been defined or has been assigned a value.
if (typeof a!= "undefined") {}, do not use if (a) because an error occurs if a does not exist (not declared).
typeof typically only returns the following results when detecting an object type:
number,boolean,string,function,object,undefined.
For Array,null, custom objects, etc. use typeof to return object,
This is precisely the limitation of TypeOf.
*/
var num = new number (1);
var arr = [1,2,3];
Alert (typeof num); Object rather than number
Alert (typeof arr); Object rather than array
Alert (typeof null); Object
/***** 3, through instanceof *****/
/* Use the instanceof operator to determine whether an object is an instance of a class.
If the 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 created by subclasses of class.
*/
function T () {};
T.prototype = Array.prototype;
T.prototype = [];
var x = new T ();
Alert (x instanceof T);//Eject True
Alert (x instanceof Array);//Eject True
Alert (x instanceof Object);//Eject True
/*
Therefore, it is not reliable to judge the data type by instanceof.
Because the prototype chain of an object (here X) can be very long, the type of each prototype can be different.
In addition in the IFRAME can also be error prone:
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 description of the parent page and the embedded iframe in the object is different, can not be mixed together to use.
Change to Top.a instanceof top. Array returns True
*/
/***** 4, through Object.prototype.toString.call () *****/
/*
The Object.prototype.toString.call () function is:
1, get the object's class name (object type).
2, and then combine [object, acquired class name] and return.
Objects that can be used to determine types such as Array,date,function
*/
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]
Expanded Display 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 A () {}
Window.utils.isFunction (A); True
Window.utils.isObject (New A ()); True
Window.utils.isArray ([]); True
/*
Such frameworks as jquery use this method to determine the type of object, so this method can be used as an authoritative method of judgment.
However, if you rewrite the Object.prototype.toString method, it can then be used to determine that the data type may be wrong,
Therefore, generally do not rewrite the Object.prototype.toString method.
*/
/********** III: Inheriting **********/
/*
JS inheritance and closures, almost every one want to delve into JS friends have to discuss the problem, so all kinds of relevant information everything.
JS inherited code version is very much, but the principle is the same, the core is the use of the prototype object.
In order to be similar to other object-oriented language styles, most of them use "class" style simulation.
The detailed principle of inheritance no longer repeat, there are many information on the Internet.
Here's an example: the inheritance written by jquery author John Resig.
(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,
-Cannot invoke the prototype method init at the creation phase of the class
-We have elaborated on this issue in the third article in this series
Fntest is a regular expression that may be evaluated (/\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 ie7.0,chrome2.0,ff3.5 and this test returns TRUE.
-so I guess this is true for fntest most of the cases: Fntest =/\b_super\b/;
var initializing = false, Fntest =/xyz/.test (function () {xyz;})? /\b_super\b/:/.*/;
Base class constructors
This is the window, so the entire code opens up a window-window to the outside world. 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 specifically points to what is not defined, but depends on how the function is invoked
-we already know that extend is definitely called as a method, not as a constructor
-so this here is not object, but function (that is Class), then This.prototype is the prototype object of the parent class.
-Note: _super points to the prototype object of the parent class, which we will encounter many times in the following code
var _super = This.prototype;
Complete inheritance by pointing the subclass's 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 is optimized by the author, so read it very blunt, I will be in the back of the detailed
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 comment code can be explained.
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 good at camouflage OH
-Use a local variable with the same name to overwrite the global variable, which is very confusing.
-If you think it's 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 above, this is the function local variable inside the Window.class
function Class () {
When instantiating a class, invokes the prototype method init
if (!initializing && this.init)
This.init.apply (this, arguments);
}
Prototype of subclasses point to instances of the parent class (key to completing inheritance)
Class.prototype = prototype; Class refers to the class at the top, not the first window. Class
Fixed constructor pointing error
Can Class.prototype.constructor = Class be used to correct???
Class.constructor = Class;
The subclass automatically gets the Extend method, Arguments.callee points to the currently executing function
Class.extend = Arguments.callee;
return Class;
};
})();