1.json to string
The code copy is as follows:
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. Convert timestamp to Date
The code copy is as follows:
function fromUnixTime(timeStamp) {
if (!timeStamp || timeStamp < 1000 || timeStamp == ' ') return "";
var theDate = new Date(parseInt(timeStamp) * 1000);
return theDate;
}
3.Data-format
The code copy is as follows:
// Author: meizz
// Extension of Date, convert Date into String in the specified format
// 1-2 placeholders can be used for month (M), day (d), hour (h), minute (m), seconds (s), and quarter (q).
// Year (y) can be used with 1-4 placeholders, millisecond (S) can only use 1 placeholder (it is a 1-3 digit number)
// example:
// (new Date()).Format("yyyy-MM-dd hh:mm:ss.S") ==> 2012-12-02 08:12:04.423
// (new Date()).Format("yyyy-Md h:m:sS") ==> 2012-12-02 8:12:4.18
Date.prototype.Format = function(fmt) {
var o = {
"M+": this.getMonth() + 1, //month
"d+": this.getDate(), //Day
"h+": this.getHours(), //hours
"m+": this.getMinutes(), //min
"s+": this.getSeconds(), //sec
"q+": Math.floor((this.getMonth() + 3) / 3), //Quarterly
"S": this.getMilliseconds() //ms
};
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 date
The code copy is as follows:
function addDay(number) {
return fromUnixTime(new Date().getTime() / 1000 + 24 * 60 * 60 * number);
}
5. When using an iframe, the mutual call between the parent form and the child form
The code copy is as follows:
// Parent form calls functions in child form
window.frames['ifm_id'].valueChange("id_101");
// The child form calls the parent form's function
parent.refreshTree("nodeId_202");
6. Popup form and return value
The code copy is as follows:
// Popup form
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 return value in pop-up form
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]
The code copy is as follows:
// 1. Global scope
var id = "global variable"; // 1.1 Variable defined outside the function
function showMsg(){
message = "global message";// 1.2 Variables that are directly assigned without definition
// Define as a global variable when used for the first time
}
// 2. Function scope
function doCheck(){
var data = "function data";// 2.1 Variables defined inside the function
}
8. JavaScript inheritance mechanism
The code copy is as follows:
// 1. Object impersonation inheritance
function Person(strName){
// private fields
var name = strName;
// public methods
this.getName = function(){
return name;
};
}
function Student(strName,strSchool){
// Define the properties and methods of the parent class
this.parent = Person;
this.parent(strName);
delete this.parent; // Delete temporary variable parent
// Define new properties and methods
// private fields
var school = strSchool;
// public methods
this.getSchool = function(){
return school;
};
}
// 2. Call(..) or apply(..) inheritance of the Funtion object
// The difference between call and apply is:
// The second parameter of call is a variable parameter;
// The second parameter of apply is Array;
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 properties and methods of the parent class
Animal.call(this,strName,intAge);
// Animal.apply(this,new Array(strName,intAge));
// Define new properties and methods
// private fields
var color = strColor;
// public methods
this.getInfo = function(){
return "name:" + this.getName() + "/n"
+ "age:" + this.getAge() + "/n"
+ "color:" + color;
};
}
// 3. prototype inheritance
// Prototype declared properties and methods are shared by all objects
// prototype will only be used when reading attributes
Function.prototype.extend = function(superClass){
// The F here is to avoid subclasses accessing properties this.xxx in parent class
function F(){};
F.prototype = superClass.prototype;
// Parent class constructor
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
The code copy is as follows:
// thisArg represents the object indicated by this when fun is inside
// call & apply will immediately execute fun and return the result
var result = fun.call(thisArg,arg1,...);
var result = fun.apply(thisArg,[argsArray]);
// thisArg represents the object indicated by this when fun is inside
// bind returns an anonymous function
var tmpfun = fun.bind(thisArg);
var result = tmpfun(arg1,...);
The code copy is as follows:
<script type="text/javascript">
/**
* Extend the function's functionality
*/
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 will be executed immediately]
var tmpfun = child.getName.bind(parent);// bind will not be executed immediately
alert(tmpfun(3)); // show 3 parents
</script>
10. js "==" Operator
The code copy is as follows:
Conversion rules
If an operand is a Boolean value, convert it to a number before comparison: false -> 0, true -> 1;
If one operand is a number and the other operand is a string, then convert the string to a number before comparison;
If one operand is an object and the other is a number or a string, the object will be converted to a primitive type before comparison.
The engine will first try to call valueOf(), if valueOf() does not have override or returns an object,
Then the engine will try to call toString(), and if toString() does not have override or returns an object, an exception is thrown;
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 will return false if compared to other values.
But null == null, undefined == undefined, null == undefined;
null and undefined cannot be converted to other values when participating in the comparison;