Javascript Framework Design: Study Notes-seed module _ javascript skills

Source: Internet
Author: User
This article is the Reading Notes of the first chapter of situ's javascript framework design. It records what you think is important and shares it with you. 1. namespace:

The namespace in js is extended using the object attributes. For example, if you define an object A, object A has attributes B and C, and both attributes B and C are objects. Therefore, if A = {B :{}, C :{}}, you can define the same method and attribute in object B and Object C. Therefore, B and C are different namespaces. We can call the methods in object B and C through A. B. like (), A. C. like. Of course, A belongs to the properties in the window object.

However, a conflict occurs when jquery. js and prototype. js are introduced to the boke. jsp page (they all add the $ attribute to the window object.

Therefore, noConflict () conflicts exist in jquery. js. Execution Process: The page first introduces prototype. prototype occupies the $ attribute of the window. When jquery is introduced, jquery stores the $ attribute of the previous window in _ $, then use the $ attribute. In this case, you can call the jquery method through $. If you want to use prototype instead of jquery, you can call $. noConflict (). Then $ is restored to a prototype object. Then you can use the prototype method through $.

The Code is as follows:


Var _ $ = window. $, _ jQuery = window. jQuery;
NoConflict: function (deep ){
Window. $ =_$;
If (deep) window. jQuery = _ jQuery;
Return jQuery; // return value. You can assign values to other variable names, such as chaojidan, so that you can call the methods in jQuery through chaojidan.
}

2. object extension:

If the namespace object is available, we need to extend the function. For example, I need to copy all the attributes and methods of object A to object B. I don't need to write code in object B one by one.

The Code is as follows:


Function mix (target, source ){
Var args = []. slice. call (arguments), I = 1,
IsCover = typeof args [args. length-1] = "boolean "? Args. pop (): true; // do not write. The default value is true, and the default value is overwrite.
If (args. length = 1 ){
Target =! This. window? This :{};
// If there is only one object parameter, this object is extended. For example, if I call mix (B) in the context of object A, this Is A. Therefore, B's attributes and methods are added to object. However, if you call mix (B) in the window, the properties and methods in object B will be added to an empty object and the empty object will be returned, to avoid overwriting the properties and methods of the same name in the window object. (Only window objects have window attributes)
I = 0;
}
While (source = args [I ++]) {
For (key in source ){
If (isCover |! (Key in target) // if it is overwritten, it is directly assigned a value. If it is not overwritten, it first determines whether the key exists in the target object. If it exists, it is not assigned a value.
{
Target [key] = source [key];
}
}
}
Return target;
}

Large company interviewers like to check the array. You can check that each item in the array can be an object, and objects A and B have the same attributes and methods, but they are also not equal. Strings and numbers, such as 123 and 123, can be found on the Internet.

3. array-based:

There are many array objects in the browser, such as arguments, document. forms, document. links, form. elements, document. getElementsByTagName, and childNodes (HTMLCollection, NodeList ).

There is also a special way to write custom objects

The Code is as follows:


Var arrayLike = {
0: "",
1: "B ",
Length: 2
}

This object is written as a jQuery object.

We need to convert the above class array object into an array object.

[]. The slice. call method can solve this problem. However, for htmlcollections in earlier versions of IE, NodeList is not a subclass of objects and cannot use the []. slice. call method.

Therefore, we can rewrite a slice method.

The Code is as follows:


A. slice = window. dispatchEvent? Function (nodes, start, end) {return []. slice. call (nodes, start, end );}
// If the dispatchEvent attribute exists in the window, it indicates that the []. slice. call method is supported and the function is detected.
: Function (nodes, start, end ){
Var ret = [], n = nodes. length;
If (end = undefined | typeof end = "number" & isFinite (end) {// & the priority is higher than |, so the end is not written, or the end is a finite number.
Start = parseInt (start, 10) | 0; // If start does not exist or is not a number, the value is 0.
End = undefined? N: parseInt (end, 10); // If end does not exist, the value is n.
If (start <0) start + = n;
If (end <0) end + = n;
If (end> n) end = n;
For (var I = start; I Ret [I-start] = nodes [I]; // earlier IE versions use the array assignment form
}
}
Return ret;
}

4. Type Determination:

Js has five simple data types: null, undefined, boolean, number, and string.

There are also complex data types: Object, Function, RegExp, Date, custom Object, such as: Person.

Typeof is generally used to judge boolean, number, string, instanceof. It is generally used to determine the object type. But they all have defects. For example, if the Array instance in firame is not the Array instance of the parent window, false is returned when instanceof is called. (This question was asked during school recruitment ). Typeof new Boolean (true) // "object", which wraps the object. Boolean, number, and string packaging objects, which are described in js advanced programming.

Many people use typeof document. it is very dangerous to determine whether it is IE, because Google and Firefox also like this attribute, so this situation occurs in Google's browser: typeof document. all // undefined, however, document. all // HTMLAllCollection, Which is undefined by typeof, but can be read.

However, the Object. prototype. toString. call method can be used to determine the type. This method can directly output [[Class] in the object. However, this method cannot be used for window objects in IE8 or below. You can use window = document // true document = window // false IE6, 7,8.

NodeType (1: Element 2: attribute 3: Text 9: document)

Method used to determine the type in jquery:

The Code is as follows:


Class2type = {}
JQuery. each ("Boolean Number String Function Array Date RegExp Object". split (""), function (I, name ){
Class2type ["[object" + name + "]"] = name. toLowerCase ();
// Class2type = {"[object Boolean]": boolean, "[object Number]": number, "[object String]": string, "[object Function]": function, "[object Array]": array ......}
});
JQuery. type = function (obj) {// If obj is null or undefined, the return value is the string "null", "undefined ". If not, call the toString method. If it can be called, The system determines that an error will be returned to the object (ActiveXobject objects such as windows and Dom in earlier IE versions)
Return obj = null? String (obj): class2type [toString. call (obj)] | "object ";
}

5. domReady

When Javascript is used to operate dom nodes, the dom tree must be constructed on the page. Therefore, the window. onload method is usually used. However, the onload method is executed only after all resources are loaded. To make the page respond to user operations more quickly, we only need to use js operations after the dom tree is built. You do not need to wait until all resources are loaded (images, flash ).

Therefore, the DOMContentLoaded event is triggered after the Dom tree is built. However, the earlier version of IE does not support hack.

The Code is as follows:


If (document. readyState = "complete") {// prevents the Javascript file from being loaded after the Dom file is loaded. In this case, you can use this judgment to execute the fn method (the method you want to execute ). Because after the document is loaded, the value of document. readyState is complete.
SetTimeout (fn); // asynchronous execution, which allows the subsequent code to be executed first. Here is the usage in jQuery.
}
Else if (document. addEventListener) {// supports DOMContentLoaded events
Document. addEventListener ("DOMContentLoaded", fn, false); // bubble
Window. addEventListener ("load", fn, false); // prevents js files from being loaded after the DOM tree is built. At this time, the DOMContentLoaded event will not be triggered (it has been triggered and ended), but the load event will be triggered
}
Else {
Document. attachEvent ("onreadystatechange", function () {// For iframe security in IE, sometimes onload is prioritized and sometimes not.
If (document. readyState = "complete "){
Fn ();
}
});
Window. attachEvent ("onload", fn); // always works to prevent other listening events from being obtained. In this way, at least the fn method can be triggered by the onload event.
Var top = false; // check whether it is in iframe
Try {// window. frameElement is an iframe or frame object that contains this page. If not, it is null.
Top = window. frameElement = null & document.doc umentElement;
} Catch (e ){}
If (top & top. doScroll) {// if there is no iframe and it is IE
(Function doScrollCheck (){
Try {
Top. doScroll ("left"); // in IE, if the Dom tree is built, you can call the doScroll method of html.
} Catch (e ){
Return setTimeout (doScrollCheck, 50); // continue listening if not built
}
Fn ();
})
}
}

The fn method must include removing all binding events.

Of course, IE can also use the script defer hack. The principle is that the script with defer specified will be executed after the DOM tree is built. However, this requires adding additional js files, which are rarely used in a separate library.

Usage principle: add the script tag in the document and use script. src = "xxx. js? 1.1.15 ", listen to the onreadystatechange event of the script, and execute the fn method when this. readyState =" complete.

That is to say, after DOM is built, xxx. js will execute and Its this. readyState will become complete.

The above is the Reading Notes of the first chapter of the javascript framework design. The content is relatively simplified, so that you can better understand the basic content of this chapter.

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.