Common javascript snippets are collected

  • 2020-03-30 04:30:33
  • OfStack

1. Json to strings


function json2str(o) {
    var arr = [];
    var fmt = function (s) {
        if (typeof s == 'object' && s != null) return json2str(s);
        return /^(string|number)$/.test(typeof s) ? "'" + s + "'" : s;
    };
    for (var i in o) arr.push("'" + i + "':" + fmt(o[i]));
    return '{' + arr.join(',') + '}';
}

2. Time stamp changed to Date


function fromUnixTime(timeStamp) {
    if (!timeStamp || timeStamp < 1000 || timeStamp == ' ') return "";
    var theDate = new Date(parseInt(timeStamp) * 1000);
    return theDate;
}

3. The Data - the format


//Author: meizz  < br / > //An extension to Date that converts the Date to a String  of the specified format;   < br / > //Month (M), day (d), hour (h), minute (M), second (s), quarter (q) can use 1-2 placeholders, & PI;   < br / > //Year (y) can use 1-4 placeholders, millisecond (S) can only use 1 placeholder (is 1-3 digits)& PI;   < br / > //Example:     < br / > // (new Date()).Format("yyyy-MM-dd hh:mm:ss.S") ==> 2012-12-02 08:12:04.423  
// (new Date()).Format("yyyy-M-d h:m:s.S")      ==> 2012-12-02 8:12:4.18  
Date.prototype.Format = function(fmt) { 
    var o = {
        "M+": this.getMonth() + 1,                 //In     < br / >         "d+": this.getDate(),                    //Day     < br / >         "h+": this.getHours(),                   //Hours     < br / >         "m+": this.getMinutes(),                 //Points     < br / >         "s+": this.getSeconds(),                 //Seconds     < br / >         "q+": Math.floor((this.getMonth() + 3) / 3), //Quarter     < br / >         "S": this.getMilliseconds()             // milli Seconds     < br / >     };
    if (/(y+)/.test(fmt))
        fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt))
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
};

4. Add n days to the date


function addDay(number) {
        return fromUnixTime(new Date().getTime() / 1000 + 24 * 60 * 60 * number);
}

5. Calls between parent and child forms when using iframe


//The parent form calls the function & NBSP; inside the child form; < br / > window.frames['ifm_id'].valueChange("id_101"); 
//The child form calls the parent form's function & NBSP; < br / > parent.refreshTree("nodeId_202"); 

6. Pop-up form and return value


//Pop-up form & NBSP; < br / > var url = "http://www.baidu.com"; 
win=window.showModalDialog(url,window,"dialogLeft:400;dialogTop:200;dialogWidth:560px;dialogHeight:380px;scroll:yes;menubar:no;toolbar:no;status:no;"); 
//Set the return value & NBSP on the pop-up form; < br / > var result = new Array(); 
result[0] = "id_101"; 
result[1] = "name_202"; 
window.returnValue = result; 
window.close(); 

7. Javascript scope [only global scope and function scope,javascript has no block scope]


//1. Global scope & PI; < br / > var id = "global variable";    //1.1 variable & PI defined outside the function; < br / > function showMsg(){     
    message = "global message";//1.2 undefined and directly assigned variable & NBSP; < br / >                                //        Is defined as the global variable & PI when first used; < br / > } 
//Function scope & NBSP; < br / > function doCheck(){ 
    var data = "function data";//2.1 variable & PI defined within the function; < br / > } 

8. Javascript inheritance mechanism


//1. The object impersonates inheritance & NBSP; < br / > function Person(strName){ 
    // private fields 
    var name = strName; 
    // public methods 
    this.getName = function(){ 
        return name; 
    };     

function Student(strName,strSchool){ 
    //Define the parent class's properties and methods & NBSP;         < br / >     this.parent = Person; 
    this.parent(strName); 
    delete this.parent;        //Delete the temporary variable parent ; < br / >     //Define new properties and methods & NBSP;         < br / >     // private fields 
    var school = strSchool; 
    // public methods 
    this.getSchool = function(){ 
        return school; 
    };      

//2. Call (..) of Funtion object Or apply (..) Inheritance   < br / > //      The difference between call and apply is: & NBSP; < br / > //          Call  The second parameter is a variable parameter;   < br / > //          The second parameter of apply is Array;   < br / > function Animal(strName,intAge){ 
    // private fields 
    var name = strName; 
    var age = intAge; 
    // public methods 
    this.getName = function(){ 
        return name; 
    };  
    this.getAge = function(){ 
        return age; 
    }; 

function Cat(strName,intAge,strColor){ 
    //Define the parent class's properties and methods & NBSP;         < br / >     Animal.call(this,strName,intAge); 
    // Animal.apply(this,new Array(strName,intAge)); 
    //Define new properties and methods & NBSP;         < br / >     // private fields 
    var color = strColor; 
    // public methods 
    this.getInfo = function(){ 
        return "name:" + this.getName() + "n" 
             + "age:" + this.getAge() + "n" 
             + "color:" + color; 
    }; 

//3. Prototype inherits & NBSP; < br / > //      Prototype declares properties and methods that are Shared by all objects & NBSP; < br / > //      Prototype only USES & PI when reading properties; < br / > Function.prototype.extend = function(superClass){ 
    //The F here is to prevent subclasses from accessing the property this.xxx  in the parent class; < br / >     function F(){}; 
    F.prototype = superClass.prototype; 
    //Superclass constructor & NBSP; < br / >     this.superConstructor = superClass; 
    this.superClass = superClass.prototype; 
    this.prototype = new F(); 
    this.prototype.constructor = this; 
}; 
Function.prototype.mixin = function(props){     
    for (var p in props){         
        this.prototype[p] = props[p];         
    } 
}; 
function Box(){} 
Box.prototype = {     
    getText : function(){ 
        return this.text; 
    }, 
    setText : function(text){ 
        this.text = text; 
    } 
}; 
function CheckBox(){} 
CheckBox.extend(Box); 
CheckBox.mixin({ 
    isChecked : function(){ 
        return this.checked; 
    }, 
    setChecked : function(checked){ 
        this.checked = checked; 
    } 
}); 

9. Call, apply & bind


//ThisArg represents the object & NBSP; this indicates when inside the fun; < br / > //Call & apply will immediately execute the fun and return the result & NBSP; < br / > var result = fun.call(thisArg,arg1,...); 
var result = fun.apply(thisArg,[argsArray]); 
//ThisArg represents the object & NBSP; this indicates when inside the fun; < br / > //Bind returns an anonymous function & NBSP; < br / > var tmpfun = fun.bind(thisArg); 
var result = tmpfun(arg1,...); 


<script type="text/javascript"> 
/**
 * extension Function The function of the
 */ 
Function.prototype.bind = function(obj){ 
    var method = this; 
    var tmpfun = function(){ 
        return method.apply(obj,arguments); 
    }; 
    return tmpfun; 

function Parent(){ 
    this.name = "parent"; 

function Child(){ 
    this.name = "child"; 
    this.getName = function(time){ 
        return time + " " + this.name; 
    }; 

var parent = new Parent(); 
var child = new Child(); 
alert(child.getName(1));                // show 1 child 
alert(child.getName.call(parent,2));    //Show 2 parent [call & apply executes immediately]& NBSP; < br / > var tmpfun = child.getName.bind(parent);//Bind is not executed immediately & NBSP; < br / > alert(tmpfun(3));                       // show 3 parent 
</script> 

10. Js "= =" Operator


Transformation rules  
   If an operand is Boolean Value, then compare it to a number before: false -> 0, true -> 1; 
   If one operand is a number and the other is a string, convert the string to a number before comparing ; 
   If one operand is an object and the other is a number or a string, the comparison converts the object to a primitive type,  
       The engine tries to call it first valueOf(), if valueOf() There is no override Or return an object,  
       The engine tries to call toString(), if toString() There is no override Or return an object , Throws an exception ; 
   If two objects are compared, determine whether they refer to the same object ; 
   If an operand is NaN, == Will return false, != Will return true; 
   null and undefined Comparisons with other values are returned false, 
       but null == null, undefined == undefined, null == undefined; 
   When participating in comparison null and undefined You can't convert to anything else ;   


Related articles: