Advanced JavaScript functions
JS does not have the concept of class, we can use function to simulate.
Lazy load function
For example, we usually use the following JS code to create Ajax:
function createXHR () {
var xhr = null;
try{
xhr = new XMLHttpRequest(); // FF、Opera、Safari、IE7
} catch(e) {
handlerError(e);
try{
xhr = new ActiveXObject('Msxml2.XMLHTTP');
} catch (e) {
try{
xhr = ActiveXObject('Microsoft.XMLHTTP');
} catch(e) {
xhr = null;
}
}
}
return xhr;
}
function handlerError (err) {
var errXHR = err;
// ...
}
In modern network technology, AJAX technology has long been a rotten street, a web page usually contains a lot of Ajax – which leads to frequent creation of XHR, resulting in memory leakage. We can useLazy load functionTo dynamically generate XHR.
/*Inert function (effective for the second time)*/
function createXHR () {
var xhr = null;
if (typeof XMLHttpRequest != 'undefined') {
xhr = new XMLHttpRequest();
createXHR = function () {
return new XMLHttpRequest();
}
} else {
try{
xhr = new ActiveXObject('Msxml2.XMLHTTP');
createXHR = function () {
return new ActiveXObject('Msxml2.XMLHTTP');
}
} catch (e){
try{
xhr = new ActiveXObject('Microsoft.XMLHTTP');
createXHR = function () {
return new ActiveXObject('Microsoft.XMLHTTP');
}
} catch (e){
createXHR = function () {
return null;
}
}
}
}
return xhr;
}
We call the above method to create XHR, so we don’t need to judge every time when we run it for the second time,Return to XHR directly。
Coritrization of functions
Curry is a technique that transforms a function that takes multiple parameters into a function that takes a single parameter (the first parameter of the original function), and returns a new function that takes the remaining parameters and returns the result. In short, it is the combination of the parameters of two functions. For example:
function curry(fn) {
var args = Array.prototype.slice . call (arguments, 1); // take the parameter of curry and change it into an array [100]
console.log(args); // [100]
return function () {
var innerArgs = Array.prototype.slice . call (arguments); // parameter list of anonymous function [1,2]
console.log(innerArgs); // [1,2]
var finalArgs = args.concat (innerargs); // merge arrays (merge parameters)
console.log(finalArgs); // [100,1,2]
return fn.apply(null, finalArgs);
}
}
function add(num1,num2,num3) {
return num1 + num2 + num3;
}
var t = curry(add,100)(1,2);
console.info(t);
Cascade function
Cascading is an object that connects all its related things together. Such as: the following objects.
//People: hands, legs, mouth
function classPerson(){
this.hand = "";
this.foot = "";
this.leg = "";
}
classPerson.prototype = {
setHand:function(){
this.hand ='big hands';
},
setLeg:function () {
this.leg ='long legged Europa';
},
setMouse:function () {
this.mouse ='cherry mouth';
}
}
var person = new classPerson();
person.setHand();
person.setMouse();
person.setLeg();
console.log(person);
We know that the creation of human beings is a whole (it is impossible to build hands, legs and mouth first). Our current demand is that once the object of human beings is instantiated, there will be everything.
Simply modify the above code:
function classPerson(){
this.hand = "";
this.foot = "";
this.leg = "";
}
classPerson.prototype = {
setHand:function(){
this.hand ='big hands';
return this;
},
setLeg:function () {
this.leg ='long legged Europa';
return this;
},
setMouse:function () {
this.mouse ='cherry mouth';
return this;
}
}
var person = new classPerson();
person.setHand (). Setmouse(). Setleg(); // call the function
console.log(person);
We have added in each setterreturn this
Return the original object (avoid undefined after the function with no return value is executed). We can be surprised to find that the commonly used chain call of jQuery is a kind of cascade call$(‘#id’).show().hide().show().hide().show().hide();
Regular expression in JavaScript
generally speaking//
In JS, it represents a single line comment, but once we add content to the middle of the slash, for example:/TEST/
It magically becomes regular.
Declaration of pattern string
Var patt1 = new regexp ('Hello '); // mode 1
Var patt2 = / word /; // mode 2
Test method
After we get the pattern string (pattern object), we can call this method to match the string and return the specified value (true or false).
var patt = /my/;
var str = 'this is my code...';
console.log(patt.test(str)); // true
Exec method
It is similar to the match method of string, but when the pattern string is specified as global, they behave differently and return null without matching.
/hello/.exec('oh hello world'); // ["hello"]
The above two methods are the methods of the string object itself, and the following methods are the methods related to regularization in the string.
Match method
Pattern matching. The function prototype is str.mattch (pattern), return the matching result as an array.
console.log('test 123'.match(/test/g)); // [test]
Replace method
String replacement, note: this method generates a new temporary stringcopy. As shown in the figure:
Split method
Split the string into arrays according to the pattern.
console.log('Hello world,hello everyone'.split(/\s+/)); // ["Hello", "world,hello", "everyone"]
console.log ('Hello world, Hello everyone '. Split ('); // equivalent to the above method
Regular types
/pattern/attributes
Attributes are optional strings. The common attributes are “g” (global match), “I” (case insensitive) and “m” (multi line match)
console.log ('Hello world, Hello everyone '. Match (/ hello / GI)); // find Hello globally and ignore case ["hello", "hello"]
In the actual development, we can useOnline regular debugging toolTo debug our regularization, in fact, a large number of commonly used regularization are built in. If we can’t analyze other people’s regular meaning in the development, we can use the help ofCanonical analysisThe website will be displayed in the form of finite automata diagram.
Metacharacter in regularization
Metacharacters in regularization must be escaped
( [ { ^ $ | ) ? * + .]}
It should be noted that there are two ways to create regularization: literal string and literal stringnew RegExp()
Because the constructor of regexp is a string, double escape is needed in some cases
__PROTO__
__proto__
Make inheritance easier:
function Super(){};
function Sub(){};
Sub.prototype.__proto__ = Super.prototype;
This is a very useful feature, which can avoid the following tasks:
-
With the help of intermediate constructors
-
There is no need to introduce a third-party module for prototype inheritance based declaration
Accessor
You can call methods to define properties, such as:__defineGetter__
、__defineSetter__
. For exampleDate
Object defines an ago property and returns the date interval described in natural language (for example, something happened 3 seconds ago). For example:
Date.prototype.__defineGetter__('ago',function(){
var diff = ((Date.now() - this.getTime()) / 1000)
day_diff = Math.floor(diff / 86400)
return day_diff == 0 && (diff < 60 && 'just now' )
|| diff < 120 && '1 minute ago'
|| diff < 3600 && Math.floor(diff / 60) + 'minutes ago'
|| diff < 7200 && '1 hour ago'
|| diff < 86400 && Math.floor(diff / 3600) + 'hours ago'
|| day_diff == 1 && 'Yesterday'
|| diff < 7 && day_diff + ' days ago'
|| Math.ceil(day_diff / 7) + ' weeks ago'
})
var d = new Date('12/12/1990')
console.log(d.ago)