JavaScript Common code snippet collection _javascript Tips

Source: Internet
Author: User
Tags inheritance

1.json Spin String

Copy Code code 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. Time Stamp to date

Copy Code code as follows:

function Fromunixtime (timeStamp) {
if (!timestamp | | TimeStamp < 1000 | | | timeStamp = = ") return" ";
var thedate = new Date (parseint (timeStamp) * 1000);
return thedate;
}

3.data-format

Copy Code code as follows:

Author: meizz
An extension to date that converts date to a string of the specified format
Months (m), days (d), hours (h), minutes (m), seconds (s), quarter (q) can be used with 1-2 placeholders,
Year (y) you can use 1-4 placeholders, milliseconds (s) to use only 1 placeholders (1-3-digit digits)
Example:
(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,//month
"D+": this.getdate (),//day
"h+": this.gethours (),//hour
"m+": this.getminutes (),//min
"S+": This.getseconds (),//sec
"q+": Math.floor (This.getmonth () + 3)/3),//Quarter
"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]): (("+ o[k]"). substr (("" + o[k). length));
return FMT;
};

4. Add n days on date

Copy Code code as follows:

function Addday (number) {
Return Fromunixtime (New Date (). GetTime ()/1000 + * * number);
}

5. The interaction between the parent form and the subform is invoked when the IFRAME is used

Copy Code code as follows:

Functions that the parent form calls within the child window
window.frames[' ifm_id '].valuechange ("id_101");
A function that invokes a parent form on a subform
Parent.refreshtree ("nodeid_202");

6. Pop-up form and return value

Copy Code code as follows:

Pop-up 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 the return value in a 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 does not have block scope]

Copy Code code as follows:

1. Global scope
var id = "global variable"; 1.1 Variables defined outside the function
function ShowMsg () {
message = ' global message ';//1.2 A variable that is not defined and directly assigned
is defined as a global variable for the first time it is used
}
2. function scopes
function Docheck () {
var data = "function data";//2.1 variables defined within a function
}

8. JavaScript inheritance mechanism

Copy Code code as follows:

1. Object impersonating 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
Defining new attributes and methods
Private fields
var school = Strschool;
Public methods
This.getschool = function () {
return school;
};
}
2. Funtion object's call (..) or apply (..) inheritance
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));
Defining new attributes 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
Attributes and methods declared by prototype are shared by all objects
Prototype is only used when reading attributes.
Function.prototype.extend = function (superclass) {
The F here is to avoid subclasses accessing properties in the parent class This.xxx
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

Copy Code code as follows:

Thisarg represents the object as indicated in the inside of the fun
Call & Apply immediately executes the fun and returns the results
var result = Fun.call (Thisarg,arg1,...);
var result = fun.apply (Thisarg,[argsarray]);
Thisarg represents the object as indicated in the inside of the fun
Bind returns an anonymous function
var tmpfun = Fun.bind (Thisarg);
var result = Tmpfun (arg1,...);

Copy Code code as follows:

<script type= "Text/javascript" >
/**
* Extended function functions
*/
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 execute immediately]
var Tmpfun = child.getName.bind (parent);/bind does not execute immediately
Alert (Tmpfun (3)); Show 3 Parent
</script>

A. js "= =" Operator

Copy Code code as follows:

Conversion rules
If an operand is a Boolean value, it is converted to a number before the comparison: false-> 0, true-> 1;
If one operand is a number and the other operand is a string, the string is converted to a number before being compared;
If one operand is an object and the other operand is a number or a string, the object is converted to the base type before the comparison.
The engine will attempt to invoke valueof () first, if valueof () does not override or returns an object,
The engine attempts to call ToString () and throws an exception if ToString () does not override or returns an object;
If two objects are compared, they are judged to refer to the same object;
If the operand is NaN, = = returns false, and!= returns true;
Null and undefined will return false when compared with other values.
But null = null, undefined = = undefined, null = = undefined;
Null and undefined cannot be converted to other values when participating in comparisons;

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.