JavaScript advanced programming learning notes js Advanced Skills

Source: Internet
Author: User

Chapter 2 Advanced Skills
1. Advanced functions
1.1 Scope-safe Constructor
① When you directly call the constructor rather than the new operator, because this object is bound late, it will be mapped to the Global Object window, resulting in an object attribute error being added to the window.
Copy codeThe Code is as follows:
Function Person (name, age, job ){
This. name = name;
This. age = age;
This. job = job;
}
Var person = Person ("Jay", 29, "singer"); // Add the property to the window object.

② Scope Security Constructor
Copy codeThe Code is as follows:
Function Person (name, age, job ){
If (this instanceof Person ){
This. name = name;
This. age = age;
} Else {
Return new Person (name, age );
}
}

③ If the above-mentioned scope-safe constructor uses the constructor to steal the inheritance mode and does not use the prototype chain, this inheritance is likely to be damaged.
□This problem can be solved if the constructor steals a prototype chain or a parasitic combination.
Copy codeThe Code is as follows:
Function Polygon (side ){
If (this instanceof Polygon ){
This. sides = sides;
This. getArea = function {return 0 ;};
} Else {
Return new Polygon (sides );
}
}
Function Rectangle (width, height ){
Polygon. call (this, 2 );
This. width = width;
This. height = height;
This. getArea = function (){
Return this. width * this. height;
};
}
Rectangle. prototype = new Polygon ();
Var rect = new Rectangle (5, 10 );
Alert (rect. sides); // 2

1.2 inert loading Functions
① Inert loading indicates that the branch of function execution only occurs once: the first call time. During the first call, the function will be overwritten as another function that is executed in an appropriate way, so that any call to the original function will no longer be executed.
■ Advantages:
□The appropriate code to be executed is only executed when the function is actually called.
□Although the first call to this function slows down a little because of the second function call, subsequent calls will be very fast, because multiple conditions are avoided.
Copy codeThe Code is as follows:
Function create XHR (){
If (typeof XMLHttp Request! = "Undefined "){
CreateXHR = function (){
Return new XMLHttpRequest ();
};
} Else if (typeof ActiveXObject! = "Undefined "){
CreateXHR = function (){
If (typeof arguments. callee. activeXString! = "String "){
Var versions = ["MSXML2.XMLHttp. 6.0", "MSXML2.XMLHttp. 3.0", "MSXML2.XMLHttp"];
For (vai I = 0, len = versions. length; I <len; I ++ ){
Try {
Var xhr = new ActiveXObject (version [I]);
Arguments. callee. activeXString = version [I];
Return xhr;
} Catch (ex ){
// Skip
}
}
}
Return new ActiveXObject (arguments. callee. activeXString );
};
} Else {
CreateXHR = function (){
Throw new Error ("No XHR Object available .");
};
}
Return createXHR ();
}

1.3 function binding
① To create a function for function binding, you can call another function with specified parameters in a specific environment.
② A simple bind () function accepts a function and an environment, returns a function that calls a given function in a given environment, and passes all parameters intact.
Copy codeThe Code is as follows:
Function bind (fn, context ){
Return function (){
Return fn. apply (context, arguments );
};
}

③ Bound functions have more overhead than common functions-they require more memory and are a little slower because of multiple function calls-so it is best to use them only when necessary.
1.4 function kerialization
Definition: used to create a function with one or more parameters already set. The basic method of function colialization is the same as that of function binding: return a function using a closure. The difference between the two is that when a function is called, some input parameters need to be set for the return function.
Copy codeThe Code is as follows:
Function bind (fn, context ){
Var args = Array. prototype. slice. call (arguments, 2 );
Return function (){
Var innerArgs = Array. prototype. slice. call (arguments );
Var finalArgs = args. concat (innerArgs );
Return fn. apply (context, finalArgs );
};
}

2. Advanced Timer
① JavaScript is a single-threaded program, and the timer adds the code to the queue after the interval.
② After executing a set of code, the JavaScript process returns a short time, so that other processing on the page can be done.
2.1 repeated Timer
① SetInterval () adds the timer code to the queue only when there is no other code instance with the timer.
□Certain intervals will be skipped.
□The interval between multiple timer code executions may be less than expected.
② Avoid the two disadvantages of setInterval () and use setTimeout () to call:
Copy codeThe Code is as follows:
SetTimeout (function (){
// Process
If (condition ){
SetTimeout (arguments. callee, interval );
}
}, Interval );

2.2 Yielding Processes
① JavaScript long-running script constraints: if the code runs for more than a specific time or the number of specific statements, it will not continue to be executed.
② When a function takes more than ms to complete, it is best to split it into a series of small tasks that can use a timer.
③ Array Partitioning technology: Create a queue for the project to be processed, use the timer to extract the next project to be processed for processing, and then set another timer.
Copy codeThe Code is as follows:
Function chunk (array, process, context ){
SetTimeout (function (){
Var item = array. shift ();
Process. call (context, item );
If (array. length> 0 ){
SetTimeout (arguments. callee, 100 );
}
}
}

2.3 function throttling
① DOM operations require more memory and CPU time than non-DOM interactions. Consecutive attempts to perform too many DOM-related operations may cause browser suspension and sometimes even crash.
② Function throttling: Some codes cannot be repeatedly executed without interruption.
□Example
Copy codeThe Code is as follows:
Var processor = {
TimeoutId: null,
// Actual processing method
PerformProcessing: function (){
// Actual execution Method
},
// Method for initial processing call
Process: function (){
ClearTimeout (this. timeoutId );
Var that = this;
This. timeoutId = setTimeout (function (){
That. Define mprocessing ();
},100 );
}
};
// Start execution
Processor. process ();
□Simplified Mode
Function throttle (method, context ){
ClearTimeout (mehtodd. tId );
Mehtodd. tId = setTimeout (function (){
Method. call (context );
},100 );
}

3. Custom events
① An event is a design pattern called an observer. It is a technology for creating loosely coupled code.
□Objects can publish events to indicate an interesting moment in the object declaration cycle.
□Other objects can observe this object and wait for interesting moments to come and respond by running code.
② The Observer mode consists of two types of objects: the subject and the observer.
□The subject is responsible for releasing events, and the observer observes the subject by subscribing to these events.
□The subject does not know anything about the observer. It can exist independently and operate normally even if the observer is not there.
③ Custom Event: Create an object for event management to allow other objects to listen to those events.
Copy codeThe Code is as follows:
Function EventTarget (){
This. handlers = {};
}
EventTarget. prototype = {
Constructor: EventTarget,
AddHandler: function (type, handler ){
If (typeof this. handlers [type] = "undefined "){
This. handlers [type] = [];
}
This. handlers [type]. push (handler );
},
Fire: function (event ){
If (! Event.tar get ){
Event.tar get = this;
}
If (this. handlers [event. type] instanceof Array ){
Var handlers = this. handlers [event. type];
For (var I = 0, len = handlers. length; I <len; I ++ ){
Handlers [I] (event );
}
}
},
RemoveHandler: function (type, handler ){
If (this. handlers [type] instanceof Array ){
Var handlers = this. handlers [type];
For (var I = 0, len = handlers. length; I <len; I ++ ){
If (handlers [I] === handler ){
Break;
}
}
Handlers. splice (I, 1 );
}
};

④ Use EventTarget-type custom events as follows:
Copy codeThe Code is as follows:
Function handleMessage (event ){
Alert ("message received ed:" + event. message );
}
// Create a new object
Var target = new EventTarget ();
// Add an event handler
Target. addHandler ("message", handleMessage );
// Trigger the event
Target. fire ({type: "message", message: "hello world! "});
// Delete the event handler
Target. removeHandler ("message", handleMessage );

⑤ Use instance
Copy codeThe Code is as follows:
Function Person (name, age ){
EventTarget. call (this );
This. name = name;
This. age = age;
}
InheritPrototype (Person, EventTarget );
Person. prototype. say = function (message ){
This. fire ({type: "message", message: message });
};
Function handleMessage (event ){
Alert(event.tar get. name + "says:" + event. message );
}
// Create a new person
Var person = new Person ("Nicolas", 29 );
// Add an event handler
Person. addHandler ("message", handleMessage );
// Call one method on this object to trigger a message event
Person. say ("Hi there ");

4. Drag and Drop
Function: ① drag and drop ② added custom events
Copy codeThe Code is as follows:
Var DragDrop = function (){
Var dragdrop = new EventTarget ();
Var dragging = null;
Var diffX = 0;
Var diffY = 0;
Function handleEvent (event ){
// Obtain events and objects
Event = EventUtil. getEvent (event );
Var target = EventUtil. getTarget (event );
// Determine the Event Type
Switch (event. type ){
Case "mousedown ":
If (target. className. indexOf ("draggable")>-1 ){
Dragging = target;
DiffX = event. clientX-target. offsetLeft;
DiffY = event. clientY-target. offsetTop;
Dragdorp. fire (
{
Type: "dragstart ",
Target: dragging,
X: event. clientX,
Y: event. clientY
}
);
Break;
Case "mousemove ":
If (dragging! = Null ){
// Obtain the event
Event = EventUtil. getEvent (event );
// Specify the location
Dragging. style. left = (event. clientX-diffX) + "px ";
Dragging. style. top = (event. clientY-diffY) + "px ";
// Trigger a Custom Event
Dragdrop. fire (
{
Type: "drag ",
Target: dargging,
X: event. clientX,
Y: event. clientY
}
);
}
Break;
Case "mouseup ":
Dargdorp. fire (
{
Type: "dragend ",
Target: dragging,
X: event. clientX,
Y: event. clientY
}
);
Dragging = null;
Break;
}
}
// Public interface
Dragdrop. enable = function (){
EventUtil. addHandler (document, "mousedown", handleEvent );
EventUtil. addHandler (document, "mousemove", handleEvent );
EventUtil. addHandler (document, "mouseup", handleEvent );
};
Dragdrop. disable = function (){
EventUtil. removeHandler (document, "mousedown", handleEvent );
EventUtil. removeHandler (document, "mousemove", handleEvent );
EventUtil. removeHandler (document, "mouseup", handleEvent );
};
Return dragdrop;
}();

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.