JavaScript Advanced Programming Learning Notes JS Advanced Skills _ Basics

Source: Internet
Author: User
Tags inheritance setinterval
The 18th Chapter Advanced Technique
1. Advanced function
1.1 Constructor for scope security
① calls a constructor directly without applying the new operator, it maps to the Global object window because of the late binding of the This object, causing the object property error to increase to window.
Copy Code code as follows:

function Person (name,age,job) {
THIS.name = name;
This.age = age;
This.job = job;
}
Var person = person ("Jay", "singer"); property is added to the Window object.

② Scope Security Constructor
Copy Code code as follows:

function Person (name,age,job) {
if (this instanceof person) {
THIS.name = name;
This.age = age;
}else{
Return to new person (name,age);
}
}

③ the above scoped security constructor, if you use the constructor to steal the inheritance of the schema and do not use the prototype chain, the inheritance is likely to be corrupted.
-This problem can be solved if the constructor theft combines a prototype chain or a parasitic combination.
Copy Code code 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 Lazy Load function
① lazy Loading represents a branch of a function that occurs only once: the first time it is invoked. During the first call, the function is overwritten with another function that executes in the proper way, so that any calls to the original function do not have to be executed.
Advantages
-The appropriate code to execute occurs only when the function is actually called.
-Although the first call to the function will be slightly slower due to an additional second function call, subsequent calls will be quick, since multiple conditions are avoided.
Copy Code code 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 Bindings
① function binding to create a function, you can call another function in a specific environment with the specified parameters.
② a simple bind () function accepts a function and an environment and returns a function that invokes the given function in a given environment and passes all parameters intact.
Copy Code code as follows:

function bind (FN, context) {
return function () {
Return fn.apply (context, arguments);
};
}

③ bound functions have more overhead than normal functions-they require more memory and are slightly slower because of multiple function calls-so it is best to use them only when necessary.
1.4 Function Corrie
Definition: Used to create a function that already has one or more parameters set. The basic method of function Gerty is the same as function binding: Returns a function using a closure. The difference is that when a function is called, the return function also needs to set some incoming arguments.
Copy Code code 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, timer that adds code to the queue after the interval.
② after executing a set of code, the JavaScript process returns for a short time so that other processing on the page can be done.
2.1 Repeat Timer
①setinterval () adds the timer code to the queue only if there is no other code instance for the timer.
-some intervals are skipped.
-the interval between multiple timer code execution may be smaller than expected.
② avoids the two disadvantages of setinterval (), using a chained settimeout () Call:
Copy Code code as follows:

settimeout (function () {
Processing
if (condition) {
SetTimeout (Arguments.callee, interval);
}
},interval);

2.2 Yielding processes
①javascript long run script constraints: If the code runs more than a specific time or a specific number of statements will not let it continue to execute.
② when a function takes more than 200ms of events to complete, it is best to split into a series of small tasks that can use timers.
③ Array Block technology: Create a queue for the project to be processed, then use the timer to remove the next item to be processed, and then set another timer.
Copy Code code 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. Successive attempts to do too much DOM-related operations may cause the browser to hang and sometimes even crash.
② function Throttling idea: Some code cannot be repeated continuously without interruption.
-Sample
Copy Code code as follows:

var processor = {
Timeoutid:null,
The method of actual processing
Performprocessing:function () {
Methods of actual execution
},
Method of initial processing call
Process:function () {
Cleartimeout (This.timeoutid);
var that = this;
This.timeoutid = settimeout (function () {
That.performprocessing ();
},100);
}
};
Try to start execution
Processor.process ();
-Simplified mode
Function Throttle (Method,context) {
Cleartimeout (Mehtod.tid);
Mehtod.tid = settimeout (function () {
Method.call (context);
},100);
}

3. Custom Events
The ① event is a design pattern called an observer, a technique for creating loosely coupled code.
-An object can publish an event to represent an interesting moment in the object declaration cycle.
-Other objects can observe the object, wait for interesting moments to come and respond by running code.
The ② Observer pattern consists of two types of objects: subject and observer.
-The subject is responsible for publishing events, while observers observe the subject by subscribing to these events.
-The subject does not know anything about the observer, and it can operate independently and normally even if the observer is not present.
③ Custom Event: Creates an object that manages events, allowing other objects to listen for those events.
Copy Code code 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.target) {
Event.target = 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);
}
};

④ custom events using the Eventtarget type can be used as follows:
Copy Code code as follows:

function Handlemessage (event) {
Alert ("Message Received:" + event.message);
}
Create a new object
var target = new Eventtarget ();
Add an event handler
Target.addhandler ("message", handlemessage);
Triggering events
Target.fire ({type: ' message ', message: "Hello world!"});
To delete an event handler
Target.removehandler ("message", handlemessage);

⑤ Use Instances
Copy Code code 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.target.name + "says:" + event.message);
}
Create a new person
var person = new Person ("Nicholas", 29);
Add an event handler
Person.addhandler ("message", handlemessage);
1 methods are invoked on the object, which triggers the message event
Person.say ("Hi there");

4. Drag and Drop
Features: ① drag-and-drop ② added custom events
Copy Code code as follows:

var DragDrop = function () {
var dragdrop = new Eventtarget ();
var dragging = null;
var diffx = 0;
var diffy = 0;
function Handleevent (event) {
Getting events and objects
event = Eventutil.getevent (event);
var target = Eventutil.gettarget (event);
Determine 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) {
Get events
event = Eventutil.getevent (event);
Specify location
Dragging.style.left = (EVENT.CLIENTX-DIFFX) + "px";
Dragging.style.top = (Event.clienty-diffy) + "px";
Triggering custom Events
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.