JavaScript Framework design the seed module _javascript skills of Reading notes

Source: Internet
Author: User
Tags script tag

1. Namespaces :

JS inside the namespace is the use of object properties to expand. For example, a user defines a object with a B attribute and a C attribute under object A, while the B and C properties are objects. So a={b:{},c:{}}, then the user can define the same method in the B object and the C object, the property. So B and C belong to different namespaces. We call the method inside the B,c object, and we can call it through A.b.like (), A.c.like (). Of course a belongs to a property in the Window object.

But there is a situation where a conflict occurs when the Boke.jsp page introduces Jquery.js and prototype.js (they all add the $ attribute to the Window object).

So there is a noconflict () handling conflict inside the jquery.js. Execution process: The page first introduces the prototype, when prototype will occupy the window's $ attribute, and then introduce jquery, jquery will put the $ attribute of the previous window in the _$, and then use the $ attribute. At this point, you can invoke the JQuery method via $. When you do not need to use jquery now and want to use prototype, you can call $.noconflict (), and then the $ will revert to the prototype object. You can then use the $ prototype method.

Copy Code code as follows:

var _$ = window.$,_jquery= window.jquery;
Noconflict:function (deep) {
window.$ = _$;
if (deep) window.jquery = _jquery;
return jQuery; Returns a value that you can assign to other variable names, such as Chaojidan, so you can invoke the method in jquery via Chaojidan.
}

2. Object Extensions :

namespace objects have, then we need to extend the functionality. For example, I need to copy the properties and methods of object A to the B object. I don't have to write code in a B object.

Copy Code code 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, default to True, override by default.
if (args.length = = 1) {
target =!this.window? this:{};
If there is only one object parameter, the This object is extended. For example: I call Mix (B) in the context of a object, then this is a, so the properties and methods of B are added to object A. But if you call Mix (b) In window, the properties and methods in the B object are added to an empty object, and the empty object is returned to prevent overwriting properties and methods with the same name in the Window object. (Only Window objects have window properties)
i = 0;
}
while ((Source = args[i++])) {
For (key in source) {
if (Iscover | |!) ( Key in target)//If overridden, directly assigns the value, if does not overwrite, first determines whether the key exists in the target object, if exists, does not assign the value
{
Target[key] = Source[key];
}
}
}
return target;
}

Big company interviewers like to ask about the weight of the array, and you can go and see that each item in the array can be an object, and object A and object B are not equal even if they are the same property and method. strings and numbers, such as 123 and "123" and so on, online search, you can find a very complete method.

3. Array :

There are many class array objects in the browser, arguments,document.forms,document.links,form.elements, Document.getelementsbytagname,childnodes, etc. (htmlcollection,nodelist).

There is also a custom object that is specifically drafted

Copy Code code as follows:

var arraylike = {
0: "A",
1: "B",
Length:2
}

This object is written as a jquery object.

We need to convert the above class array object to a group of objects.

[].slice.call method can be solved. However, the htmlcollection,nodelist in the older version of IE is not a subclass of object, and the [].slice.call method is not available.

So we can rewrite a slice method.

Copy Code code as follows:

A.slice = window.dispatchevent?      function (nodes,start,end) {return [].slice.call (Nodes,start,end); }
If the window has a dispatchevent attribute it is supported [].slice.call method, capability detection.
: function (nodes,start,end) {
var ret = [],n=nodes.length;
if (end = = Undefined | | typeof end = = "Number" && isfinite (end) {//&& precedence is higher than | |, so end is not written, or end is a finite number to enter
Start = parseint (start,10) | |   0; If start does not exist or is not a number, the value is assigned to 0.
End = End = = undefined?    N:parseint (end,10); If end does not exist, the assignment is n.
if (Start < 0) Start + = n;
if (end< 0) End + = n;
if (end>n) end = n;
for (var i = start;i<end;i++) {
Ret[i-start] = nodes[i]; Low version IE uses array assignment form
}
}
return ret;
}

4. Type of judgment :

JS five kinds of simple data types are: null,undefined,boolean,number,string.

There are also complex data types: object,function,regexp,date, custom objects, such as person.

typeof is generally used to judge boolean,number,string,instanceof generally used to judge object types. But they all have flaws. For example: The array instance inside the Firame is not an instance of the parent window's array, and calling Instanceof returns FALSE. (This question was asked in 360 school strokes). typeof New Boolean (TRUE)//"Object" to wrap the object. Boolean,number,string three kinds of packaging objects, JS Advanced program programming inside has said.

A lot of people use typeof document.all to judge whether IE, in fact, this is very dangerous, because this attribute Google and Firefox also like, so in Google Browser appeared this situation: typeof document.all//undefined But, Document.all//htmlallcollection, typeof is the undefined, but can read this property value.

However, you can now use the Object.prototype.toString.call method to determine the type. This method can directly output [[Class]] inside the object. But IE8 and the following window objects cannot use this method. You can use window = = Document/True document = = window//False ie6,7,8.

NodeType (1: Elements element 2: Attribute 3: Text 9:document)

The method used to determine the type in jquery:

Copy Code code 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]: Fun Ction, "[Object Array]": Array ...}
});
Jquery.type = function (obj) {//If obj is null,undefined etc., returns the string "null", "undefined". If not, call the ToString method, if you can call to judge, Error returns object (ie lower version of Window,dom, etc. activexobject objects)
return obj = null? String (obj): class2type [Tostring.call (obj)] | | "Object";
}

5.domReady

When JS operates on a DOM node, the page must build a good DOM tree. Therefore, the Window.onload method is usually used. However, the OnLoad method is not executed until all resources have been loaded. And in order for the page to respond more quickly to the user's operation, we only need to build the DOM tree, you should use the JS operation. Instead of waiting for all resources to be loaded to the end (picture, Flash).

As a result, a domcontentloaded event occurs, which is triggered when the DOM tree is built. However, the older version of IE does not support, so there is hack.

Copy Code code as follows:

if (document.readystate = = "complete") {///In case the DOM document is loaded before loading the JS file. This is the decision to execute the FN method (the method you want to execute). Because the Document.readystate value is complete after the document has finished loading
SetTimeout (FN); Executes asynchronously, allowing the code that follows it to execute first. Here is the use of jquery, you don't have to understand.
}
else if (Document.addeventlistener) {//Support domcontentloaded Event
Document.addeventlistener ("domcontentloaded", Fn,false); Bubble
Window.addeventlistener ("Load", fn,false); In case the DOM tree is built, then the JS file is loaded. The domcontentloaded event is not triggered (the end of the trigger is triggered) and only the Load event is triggered
}
else{
Document.attachevent ("onReadyStateChange", function () {//) for the security of the IFRAME under IE, sometimes priority to the onload execution, sometimes not.
if (document.readystate = = "complete") {
FN ();
}
});
Window.attachevent ("onload", FN); It always works to prevent other listening events from being acquired so that at least the FN method can be triggered by the OnLoad event.
var top = false;//See if it's in the IFRAME
Try{//window.frameelement is an IFRAME or frame object that contains this page. None is null.
top = Window.frameelement = = null && document.documentelement;
}catch (e) {}
if (top && top.doscroll) {//If there is no iframe and is IE
(function Doscrollcheck () {
try{
Top.doscroll ("left");//ie, if the DOM tree is built, you can call the HTML DoScroll method
}catch (e) {
return settimeout (doscrollcheck,50); If you haven't built it yet, keep listening.
}
FN ();
})
}
}

The FN method must include the removal of all binding events.

Of course, IE can also use the script defer hack, the principle is that the script that specifies defer will be executed after the DOM tree is built. But this requires adding extra JS files, which are rarely used in separate libraries.

How to use: Add a script tag to a document and monitor the script onreadystatechange event with script.src = "Xxx.js", and execute the FN method when this.readystate = = "complete".

That is, when the DOM is built, Xxx.js executes, and its this.readystate becomes complete.

The above is the first chapter of JavaScript framework design reading notes, the content is more concise, convenient for everyone to better understand the basic content of this chapter.

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.