Home  >  Article  >  Web Front-end  >  JavaScript Advanced Programming Study Notes js Advanced Skills_Basic Knowledge

JavaScript Advanced Programming Study Notes js Advanced Skills_Basic Knowledge

WBOY
WBOYOriginal
2016-05-16 18:01:56876browse

Chapter 18 Advanced Skills
1. Advanced Functions
1.1 Scope-Safe Constructor
①When the constructor is called directly without using the new operator, due to the late binding of this object, it will be mapped On the global object window, causing object property errors to be added to the window.

Copy code The code is as follows:

function Person(name,age,job){
this.name = name;
this.age = age;
this.job = job;
}
Var person = Person("Jay",29,"singer"); // Properties are added to the window object.

②Scope safe constructor
Copy code The 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);
}
}

③The above scope-safe constructor, if you use the constructor to steal the inheritance of the pattern and do not use the prototype chain, then This inheritance is likely to be broken.
□ This problem can be solved if constructor stealing is combined with prototype chaining or parasitic composition.
Copy code The 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 Lazy loading function
① Lazy loading means that the branch of function execution will only happen once: the first call when. During the first call, the function is overwritten with another function that is executed in an appropriate manner, so that any call to the original function does not have to go through the branch of execution.
■Advantages:
□Appropriate code to be executed only when the function is actually called.
□Although the first call to this function will be slightly slower due to the extra second function call, subsequent calls will be fast because multiple conditions are avoided.
Copy code The 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
① Function binding To create a function, you can specify parameters in a specific environment Call another function.
②A simple bind() function accepts a function and an environment, and returns a function that calls the given function in the given environment, passing all parameters intact.
Copy code The code is as follows:

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

③Bound functions have more overhead than ordinary functions - They require more memory and are also slightly slower due to multiple function calls - so are best used only when necessary.
1.4 Function currying
Definition: Used to create a function with one or more parameters set. The basic approach to function currying is the same as function binding: use a closure to return a function. The difference between the two is that when the function is called, the return function also needs to set some incoming parameters.
Copy code The 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 code to the queue after the interval.
②After executing a set of code, the JavaScript process returns for a short period of time so that other processing on the page can be carried out.
2.1 Duplicate timers
①setInterval() only adds timer code to the queue if there are no other instances of code for this timer.
□Some intervals will be skipped.
□The interval between multiple timer code executions may be smaller than expected.
②Avoid the two shortcomings of setInterval() and use chained setTimeout() calls:
Copy code The code is as follows:

setTimeout(function(){
//Processing
if(condition){
setTimeout(arguments.callee, interval);
}
}, interval);

2.2 Yielding Processes
① JavaScript long-running script restrictions: If the code runs for more than a specific time or a specific number of statements, it will not continue to execute.
②When a function takes more than 200ms to complete, it is best to divide it into a series of small tasks that can use timers.
③Array blocking technology: Create a queue for the items to be processed, then use a timer to take out the next item to be processed, and then set another timer.
Copy code The 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. Continuous attempts. Performing too many DOM-related operations may cause the browser to hang or even crash.
②Function throttling idea: Some code cannot be executed continuously without interruption.
□Example
Copy code The code is as follows:

var processor = {
timeoutId : null,
/ /The actual processing method
performProcessing: function(){
//The actual execution method
},
//The initial processing call method
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
①Events are a design pattern called observers, which is a technique for creating loosely coupled code.
□Objects can publish events to indicate that an interesting moment in the object's lifecycle has arrived.
□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, and observers observe the subject by subscribing to these events.
□The subject does not know anything about the observer, it can exist independently and function normally even if the observer is not present.
③Custom events: Create an object that manages events and let other objects listen to those events.
Copy code The 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.target){
event.target = this;
}
if(this.handlers[event.type] instanceof Array){
var handlers = this.handlers[event.type];
for(var i=0,len=handlers.length; ihandlers[i](event);
}
}
},
removeHandler : function(type, handler){
if(this.handlers[type] instanceof Array){
var handlers = this.handlers[type];
for(var i=0,len=handlers.length; iif(handlers[i] === handler){
break;
}
}
Handlers.splice(i,1);
}
};

④使用EventTarget类型的自定义事件可以如下使用:
复制代码 代码如下:

function handleMessage(event){
alert("message received:" event.message);
}
//创建一个新对象
var target = new EventTarget();
//添加一个事件处理程序
target.addHandler("message",handleMessage);
//触发事件
target.fire({type:"message",message:"hello world!"});
//删除事件处理程序
target.removeHandler("message",handleMessage);

⑤使用实例
复制代码 代码如下:

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);
}
//创建新person
var person = new Person("Nicholas",29);
//添加一个事件处理程序
Person.addHandler("message",handleMessage);
//在该对象上调用1个方法,它触发消息事件
person.say("Hi there");

4.拖放
功能:①拖放②添加了自定义事件
复制代码 代码如下:

var DragDrop = function(){
var dragdrop = new EventTarget();
var dragging = null;
var diffX = 0;
var diffY = 0;
function handleEvent(event){
//获取事件和对象
event = EventUtil.getEvent(event);
var target = EventUtil.getTarget(event);
//确定事件类型
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){
//获取事件
event = EventUtil.getEvent(event);
//指定位置
dragging.style.left = (event.clientX - diffX) "px";
dragging.style.top = (event.clientY - diffY) "px";
//触发自定义事件
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;
}
}
//公共接口
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;
}();
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn