It is required to know & understand coding standards of java script & jquery, because it is mandatory when you develop SharePoint 2013 apps.
1.1
Naming Conventions
·
Terminology and Definitions:
·
Camel Case (camelCase): The first letter of the
word is lower case and then each first letter of the part of the word is upper
case;
·
Pascal Case (PascalCase): The first letter of the
word is upper case and then each first letter of the part of the word is upper
case;
·
Underscode Prefix (_underscore): The word begins with
underscore char and for the rest of the word use camelCase rule;
1.2
General Rules
·
Use Pascal Case for Class
names:
Ex: public class HelloWorld { ... };
·
Use Pascal Case for Method
names:
Ex: public void SayHello(string name) { ... };
·
Use Camel Case for variables
and method parameters:
Ex:
int totalCount = 0;
void SayHello(string name)
{
string fullMessage = "Hello " + name;
...
}
·
Avoid all upper case or all
lower case names;
Do not use
Hungarian notation:
Example of Hungarian
Notation:
string m_sName;
(the prefix m_ means that is a member variable and s means that is a string
data type);
·
Code Commenting
Adding comments
to your work is without doubt one of the most important factor in team working.
More than that, it also represents the best technique for keeping the code
maintainable in time. Have a look at rules below:
·
General Rules
All comments
should be written in the same language, be grammatically correct and contain
appropriate punctuation;
Use // or ///
but not /* … */;
Do not use
flower box comments
Ex:
//***************************
// flower box
//***************************
Use inline
comments to explain assumptions, known issues and algorithm insights;
Do not use
inline comments to explain obvious code. Well written code is self-documenting;
Always apply comment-blocks (///) to public, protected and internal
1.3
JavaScript Files
·
JavaScript programs should be
stored in and delivered as .js files.
·
JavaScript code should not be
embedded in HTML files unless the code is specific to a single session. Code in
HTML adds significantly to page weight with no opportunity for mitigation by
caching and compression.
·
<script src=filename.js> tags should
be placed as late in the body as possible. This reduces the effects of delays
imposed by script loading on other page components. There is no need to use the
language or type attributes. It is the server, not the script tag, that
determines the MIME type.
1.4
Indentation
·
The unit of indentation is four
spaces. Use of tabs should be avoided because there still is not a standard for
the placement of tab stops.
1.5
Line Length
·
Avoid lines longer than 80
characters. When a statement will not fit on a single line, it may be necessary
to break it. Place the break after an operator, ideally after a comma. A break
after an operator decreases the likelihood that a copy-paste error will be
masked by semicolon insertion. The next line should be indented 8 spaces.
1.6
Comments
·
Be generous with comments. It
is useful to leave information that will be read at a later time by people
(possibly yourself) who will need to understand what you have done. The
comments should be well-written and clear, just like the code they are annotating.
·
It is important that comments
be kept up-to-date. Erroneous comments can make programs even harder to read
and understand.
·
Make comments meaningful. Focus
on what is not immediately visible. Don't waste the reader's time with stuff
like
·
i = 0; // Set i to zero.
·
Generally use line comments.
Save block comments for formal documentation and for commenting out.
1.7
Variable Declarations
·
All variables should be
declared before used. JavaScript does not require this, but doing so makes the
program easier to read and makes it easier to detect undeclared variables that
may become implied global.
Implied global variables should never be used.
·
The var statements should be
the first statements in the function body.
·
It is preferred that each
variable be given its own line and comment. They should be listed in alphabetical order.
var currentEntry; // currently selected table entry
var level; // indentation
level
var size; // size of table
·
JavaScript does not have block
scope, so defining variables in blocks can confuse programmers who are
experienced with other C family languages. Define all variables at the top of
the function.
·
Use of global variables should
be minimized. Implied global variables should never be used.
·
Use
strict mode. The rules for declaring variables in JavaScript are
fairly relaxed. If you omit the var keyword in a variable
declaration, the variable is implicitly given global scope. This means you can
accidentally declare a new global variable without realizing it, as illustrated
in the following example:
function
someFunction() {
var errorCode = 100; // Declares a local
variable named errorCode.
count = 0; // Implicitly declares a global
variable named count;
...
}
To avoid accidentally
declaring global variables by omitting the var keyword,
you can use strict mode as follows:
function
someFunction() {
"use strict";
// Other statements.
}
When you use strict mode,
you will get an error if you try to declare a variable without using var;
JavaScript will not
automatically promote the variable to global scope.
·
Because JavaScript is very loose with rules
concerning variable and object definitions, you should be sure to always use
strict JavaScript in your apps. Strict JavaScript is an improved version of
JavaScript. You can enable it by adding the line “use strict” at the top of any
library or function. Strict JavaScript will prevent you from making many common
mistakes in your code. The following lists some of the key restrictions enabled
by strict JavaScript:
·
Cannot use a variable without declaring it
·
Cannot write to a read-only property
·
Cannot add properties to non-extensible objects
·
Cannot illegally delete functions and variables
·
Cannot define a property more than once in an
object literal
·
Cannot use a parameter name more than once in a
function
·
Cannot use reserved words, eval, or arguments, as
names for functions and variables
·
The value of this in a function is no longer the
window object
·
Cannot declare functions inside of statements
·
Cannot change the members of the arguments array
1.9
Function Declarations
·
All functions should be
declared before they are used. Inner functions should follow the var statement.
This helps make it clear what variables are included in its scope.
·
There should be no space
between the name of a function and the ( (left parenthesis) of its parameter
list. There should be one space between the ) (right parenthesis) and the { (left
curly brace) that begins the statement body. The body itself is indented four
spaces. The } (right curly brace) is aligned with the line containing the
beginning of the declaration of the function.
function outer(c, d) {
var e = c * d;
function inner(a, b) {
return (e * a) + b;
}
return inner(0, 1);
}
·
This convention works well with
JavaScript because in JavaScript, functions and object literals can be placed
anywhere that an expression is allowed. It provides the best readability with
inline functions and complex structures.
function getElementsByClassName(className) {
var results = [];
walkTheDOM(document.body, function (node) {
var a; // array
of class names
var c = node.className; // the node's classname
var i; // loop
counter
// If the node has a class name, then
split it into a list of simple names.
// If any of them match the requested
name, then append the node to the set of results.
if (c) {
a = c.split(' ');
for (i = 0; i < a.length; i
+= 1) {
if (a[i] === className) {
results.push(node);
break;
}
}
}
});
return results;
}
·
If a function literal is
anonymous, there should be one space between the word function and the ( (left
parenthesis). If the space is omited, then it can appear that the function's
name is function, which is an incorrect reading.
div.onclick = function (e) {
return false;
};
that = {
method: function () {
return this.datum;
},
datum: 0
};
·
Use of global functions should
be minimized.
·
When a function is to be
invoked immediately, the entire invocation expression should be wrapped in
parens so that it is clear that the value being produced is the result of the
function and not the function itself.
var collection = (function () {
var keys = [], values = [];
return {
get: function (key) {
var at = keys.indexOf(key);
if (at >= 0) {
return values[at];
}
},
set: function (key, value) {
var at = keys.indexOf(key);
if (at < 0) {
at = keys.length;
}
keys[at] = key;
values[at] = value;
},
remove: function (key) {
var at = keys.indexOf(key);
if (at >= 0) {
keys.splice(at, 1);
values.splice(at, 1);
}
}
};
}());
1.10
Names
·
Names should be formed from the
26 upper and lower case letters (A .. Z, a .. z), the 10 digits (0 .. 9), and _
(underbar). Avoid use of international characters because they may not read
well or be understood everywhere. Do not use $ (dollar sign) or \ (backslash)
in names.
·
Most variables and functions
should start with a lower case letter.
·
Constructor functions which
must be used with the new prefix should start with a capital letter. JavaScript
issues neither a compile-time warning nor a run-time warning if a required new
is omitted. Bad things can happen if new is not used, so the capitalization
convention is the only defense we have.
·
Global variables should be in
all caps. (JavaScript does not have macros or constants, so there isn't much
point in using all caps to signify features that JavaScript doesn't have.)
1.11
Statements
Simple Statements
·
Each line should contain at
most one statement. Put a ; (semicolon) at the end of every simple statement.
Note that an assignment statement which is assigning a function literal or
object literal is still an assignment statement and must end with a semicolon.
·
JavaScript allows any
expression to be used as a statement. This can mask some errors, particularly
in the presence of semicolon insertion. The only expressions that should be
used as statements are assignments and invocations.
Compound Statements
·
Compound statements are
statements that contain lists of statements enclosed in { } (curly braces).
·
The enclosed statements should
be indented four more spaces.
·
The { (left curly brace) should
be at the end of the line that begins the compound statement.
·
The } (right curly brace)
should begin a line and be indented to align with the beginning of the line
containing the matching { (left curly brace).
·
Braces should be used around
all statements, even single statements, when they are part of a control
structure, such as an if or for statement. This makes it easier to add
statements without accidentally introducing bugs.
Whitespace
·
Blank lines improve readability
by setting off sections of code that are logically related.
·
Blank spaces should be used in
the following circumstances:
·
A keyword followed by ( (left
parenthesis) should be separated by a space.
while (true) {
·
A blank space should not be
used between a function value and its ( (left parenthesis). This helps to
distinguish between keywords and function invocations.
·
All binary operators except .
(period) and ( (left parenthesis) and [ (left bracket) should be separated from
their operands by a space.
·
No space should separate a
unary operator and its operand except when the operator is a word such as
typeof.
·
Each ; (semicolon) in the
control part of a for statement should be followed with a space.
·
Whitespace should follow every
, (comma).
1.12
for-in loops
These loops are to be used only for
iterating over keys in an object/map/hash. They are often incorrectly used to
loop over the elements in an Array. This is however very error
prone because it does not loop from 0 to length - 1 but
over all the present keys in the object and its prototype chain. Here are a few
cases where it fails:
function printArray(arr) {
for (var key in arr) {
print(arr[key]);
}
}
printArray([0,1,2,3]); // This works.
var a = new Array(10);
printArray(a); // This is wrong.
a =
document.getElementsByTagName('*');
printArray(a); // This is wrong.
a = [0,1,2,3];
a.buhu = 'wine';
printArray(a); // This is wrong again.
a = new Array;
a[3] = 3;
printArray(a); // This is wrong again.
Always use normal for loops when using
arrays.
function printArray(arr) {
var l = arr.length;
for (var i = 0; i < l; i++) {
print(arr[i]);
}
}
1.13
Associative arrays
Array should never be used as a
map/hash/associative array. Associative Arrays are
not allowed - more precisely you are not allowed to use non number indexes for
arrays. If a map/hash is required Object should be used instead
of Array since the features that are required are actually features
of Object and not of Array. Array just happens to
extend Object (like any other object in JS and
therefore you might as well have used Date, RegExp or String).
1.14
Multi-line strings
Slashes should
not be used:
var myString = 'A rather long string of English text, an error message \
actually that just keeps going and going -- an error \
message to make the Energizer bunny blush (right through \
those Schwarzenegger shades)! Where was I? Oh yes, \
you\'ve got an error and all the extraneous whitespace is \
just gravy. Have a nice day.';
The whitespace
at the beginning of each line can't be safely stripped at compile time;
whitespace after the slash will result in tricky errors; and while most script
engines support this, it is not part of ECMAScript.
String
concatenation should be used instead:
var myString = 'A rather long string of English text, an error message ' +
'actually that just keeps going and going -- an error ' +
'message to make the Energizer bunny blush (right through ' +
'those Schwarzenegger shades)! Where was I? Oh yes, ' +
'you\'ve got an error and all the extraneous whitespace is ' +
'just gravy. Have a nice day.';
1.15
Array & Object Literals
Array and Object literals
should be used instead of Array and Object constructors. Array constructors are error-prone due to
their arguments.
// Length is 3.
var a1 = new Array(x1, x2, x3);
// Length is 2.
var a2 = new Array(x1, x2);
// If x1 is a number and it is a
natural number the length will be x1.
// If x1 is a number but not a
natural number this will throw an exception.
// Otherwise the array will have one
element with x1 as its value.
var a3 = new Array(x1);
// Length is 0.
var a4 = new Array();
Because of this, if someone changes the code
to pass 1 argument instead of 2 arguments, the array might not have the
expected length.
To avoid these kinds of weird cases, the
more readable array literal should always be used.
var a = [x1, x2, x3];
var a2 = [x1, x2];
var a3 = [x1];
var a4 = [];
Object constructors don't have the same
problems, but for readability and consistency object literals should be used.
var o = new Object();
var o2 = new Object();
o2.a = 0;
o2.b = 1;
o2.c = 2;
o2['strange key'] = 3;
Should be written as:
var o = {};
var o2 = {
a: 0,
b: 1,
c: 2,
'strange key': 3
};
1.16
Method and property definitions
While there are several ways to attach
methods and properties to an object created via new, the preferred style for methods is:
Foo.prototype.bar = function() {
/* ... */
};
The preferred style for other properties is
to initialize the field in the constructor:
/** @constructor */
function Foo() {
this.bar = value;
}
1.17
Browser-specific code / IE
hacks
Browser-specific
javascript objects or functions should not be used.
var f = function () {
/*@cc_on if (@_jscript) { return 2* @*/ 3; /*@ } @*/
};
Conditional
Comments hinder automated tools as they can vary the JavaScript syntax tree at
runtime.
1.18
Javascript Tips & Tricks
True and False
Boolean Expressions
The following are all false in boolean
expressions:
·
null
·
undefined
·
'' the empty string
·
0 the number
But be careful, because these are all true:
·
'0' the string
·
[] the empty array
·
{} the empty object
This
means that instead of this:
you can
write this shorter code (as long as you don't expect x to be 0, or the
empty
string, or false):
And if
you want to check a string to see if it is null or empty, you could do this:
if (y != null && y != '') {
But this
is shorter and nicer:
Caution: There are many unintuitive things about
boolean expressions. Here are
some of them:
·
Boolean('0')
== true
'0' != true
·
0 != null
0 == []
0 == false
·
Boolean(null)
== false
null != true
null != false
·
Boolean(undefined)
== false
undefined != true
undefined != false
·
Boolean([])
== true
[] != true
[] == false
·
Boolean({})
== true
{} != true
{} != false
Instead
of this:
if (val) {
return foo();
} else {
return bar();
}
you can
write this:
return val ? foo() : bar();
The
ternary conditional is also useful when generating HTML:
var html = '<input
type="checkbox"' +
(isChecked ? ' checked' : '') +
(isEnabled ? '' : ' disabled') +
' name="foo">';
&& and ||
These
binary boolean operators are short-circuited, and evaluate to the last
evaluated term.
"||"
has been called the 'default' operator, because instead of writing this:
/** @param {*=} opt_win */
function foo(opt_win) {
var win;
if (opt_win) {
win = opt_win;
} else {
win = window;
}
// ...
}
you can
write this:
/** @param {*=} opt_win */
function foo(opt_win) {
var win = opt_win || window;
// ...
}
"&&"
is also useful for shortening code. For instance, instead of this:
if (node) {
if (node.kids) {
if (node.kids[index]) {
foo(node.kids[index]);
}
}
}
this
could be used:
if (node && node.kids
&& node.kids[index]) {
foo(node.kids[index]);
}
or this:
var kid = node && node.kids
&& node.kids[index];
if (kid) {
foo(kid);
}
Iterating over Node Lists
Node
lists are often implemented as node iterators with a filter. This means that
getting a property like length is O(n), and iterating over the list by
re-checking the length will be O(n^2).
var paragraphs =
document.getElementsByTagName('p');
for (var i = 0; i <
paragraphs.length; i++) {
doSomething(paragraphs[i]);
}
It is
better to do this instead:
var paragraphs =
document.getElementsByTagName('p');
for (var i = 0, paragraph; paragraph
= paragraphs[i]; i++) {
doSomething(paragraph);
}
This
works well for all collections and arrays as long as the array does not contain
things that are treated as boolean false.
In cases
of iterating over the childNodes, the firstChild and nextSibling properties can
be used.
var parentNode =
document.getElementById('foo');
for (var child =
parentNode.firstChild; child; child = child.nextSibling) {
doSomething(child);
}
1.20
Other common suggestions
{} and []
·
Use {} instead of new Object ().
Use [] instead of new Array ().
·
Use arrays when the member
names would be sequential integers. Use objects when the member names are
arbitrary strings or names.
, (comma) Operator
·
Avoid the use of the comma
operator except for very disciplined use in the control part of for statements.
(This does not apply to the comma separator, which is used in object literals,
array literals, var statements, and parameter lists.)
Block Scope
·
In JavaScript blocks do not
have scope. Only functions have scope. Do not use blocks except as required by
the compound statements.
Assignment Expressions
·
Avoid doing assignments in the
condition part of if and while statements.
Is
if (a = b) {
a correct statement? Or was
if
(a == b) {
intended? Avoid constructs that cannot
easily be determined to be correct.
=== and !== Operators.
·
It is almost always better to
use the === and !== operators. The == and != operators do type coercion. In
particular, do not use == to compare against falsy values.
Confusing Pluses and Minuses
·
Be careful to not follow a +
with + or ++. This pattern can be confusing. Insert parens between them to make
your intention clear.
total = subtotal +
+myInput.value;
is better written as
total = subtotal + (+myInput.value);
so that the + + is not misread as ++.
eval is Evil
·
The eval function is the most
misused feature of JavaScript. Avoid it.
·
eval has aliases. Do not use
the Function constructor. Do not pass strings to setTimeout or setInterval.
1.21
Exception Handling
Error Objects
·
When an exception occurs, an
object representing the error is created and thrown. The JavaScript
language defines seven types of built-in error objects. These error types
are the foundation for exception handling. Each of the error types is
described in detail below.
Error
·
The “Error” type is used to represent generic exceptions. This type of exception is most often used for implementing
user defined exceptions. ”Error” objects are instantiated by calling
their constructor as shown in the following example.
var error = new Error("error
message");
·
“Error” objects contain two properties, “name” and “message”. The “name” property specifies the type of exception (in this
case “Error”). The “message” property provides a more detailed description
of the exception. The “message” gets its value from the string passed to
the exception’s constructor. The remaining exception types represent more
specific types of errors, but they are all used in the same fashion as the
generic “Error” type.
RangeError
·
“RangeError” exceptions are
generated by numbers that fall outside of a specified range. For example,
JavaScript numbers have a toFixed()
method which takes a “digits”
argument representing the number of digits to appear after a decimal point.
This argument is expected to be between 0 and 20 (although some browsers
support a wider range). If the value of “digits” is outside of this
range, then a “RangeError” is thrown. This scenario is shown in the
following example.
var pi = 3.14159;
pi.toFixed(100000);
// RangeError
ReferenceError
·
A “ReferenceError” exception is
thrown when a non-existent variable is accessed. These exceptions
commonly occur when an existing variable name is misspelled. In the
example below, a “ReferenceError” occurs when “bar” is accessed. Note
that this example assumes that “bar” does not exist in any active scope when
the increment operation is attempted.
function foo() {
bar++; // ReferenceError
}
SyntaxError
·
A “SyntaxError” is thrown when
the rules of the JavaScript language are broken. Developers who are
familiar with languages such as C and Java are used to encountering syntax
errors during the compilation process. However, because JavaScript is an
interpreted language, syntax errors are not identified until the code is
executed. Syntax errors are unique as they are the only type of exception
that cannot be recovered from. The following example generates a syntax
error because the “if” statement is missing a closing curly brace.
if (foo) { // SyntaxError
// the closing curly brace is missing
TypeError
·
A “TypeError” exception occurs
when a value is not of the expected type. Attempting to call a
non-existent object method is a common cause of this type of exception.
The following example creates an empty object named “foo” and then
attempts to invoke its bar() method. Since bar() is not defined, a
“TypeError” is thrown upon the attempted invocation.
var foo = {};
foo.bar(); // TypeError
URIError
·
A “URIError” exception is
thrown by methods such as encodeURI () and decodeURI () when they encounter a
malformed URI. The following example generates a “URIError” while
attempting to decode the string “%”. The “%” character represents the
beginning of a URI escape sequence. Since nothing follows the “%” in this
example, the string is an invalid escape sequence, and therefore a malformed
URI component.
decodeURIComponent ("%"); //
URIError
EvalError
·
“EvalError” exceptions are
thrown when the eval() function is used improperly. These exceptions are
not used in the most recent version of the EcmaScript standard. However,
they are still supported in order to maintain backwards compatibility with
older versions of the standard.
1.22
Handling Exceptions
·
Now that we know what
exceptions are, it’s time to learn how to stop them from crashing our programs.
JavaScript handles exceptions via the “try…catch…finally” statement.
A generic example statement is shown below.
try {
// attempt to execute this code
} catch (exception) {
// this code handles exceptions
} finally {
// this code always gets executed
}
·
The first part of a
“try…catch…finally” statement is the “try” clause. The “try” clause is
mandatory, and is used to delimit a block of code that the programmer suspects
could generate an exception. The “try” clause must be followed by one or
both of the “catch” and “finally” clauses.
The “catch” Clause
·
The second part of
“try…catch…finally” is the “catch” clause. The “catch” clause is a block
of code that is only executed if an exception occurs in the “try” clause.
Although the “catch” clause is optional, it isn’t possible to truly
handle an exception without one. This is because the “catch” clause stops
the exception from propagating through the call stack, allowing the program to
recover. If an exception occurs within the “try” block, then control is
immediately passed to the “catch” clause. The exception that occurred is
also passed to the “catch” block for processing. The following example
shows how a “catch” clause is used to handle a “ReferenceError”. Note that
the “ReferenceError” object is available in the “catch” clause via the
“exception” variable.
try {
foo++; // ReferenceError
} catch (exception) {
var message = exception.message;
//
handle the exception
}
·
Complex applications can
generate a variety of exceptions. In such cases, the “instanceof”
operator can be used to differentiate between the various types of exceptions.
In the following example, assume that the “try” clause can generate
several types of exceptions. The corresponding “catch” clause uses
“instanceof” to handle “TypeError” and “ReferenceError” exceptions separately
from all other types of errors.
try {
// assume an exception occurs
} catch (exception) {
if
(exception instanceof TypeError) {
// Handle TypeError exceptions
}
else if (exception instanceof ReferenceError) {
//
Handle ReferenceError exceptions
} else {
//
Handle all other types of exceptions
}
}
The “finally” Clause
·
The last component of the
“try…catch…finally” statement is the optional “finally” clause. The
“finally” clause is a block of code that is executed after the “try” and
“catch” clauses, regardless of any errors. The “finally” clause is useful
for including clean up code (closing files, etc.) that needs to be executed no
matter what. Note that the “finally” clause is even executed if an
exception occurs that is not caught. In such a scenario, the “finally”
clause is executed and then the thrown exception proceeds normally.
·
One interesting note about the
“finally” clause is that it will be executed even if the “try” or “catch”
clause executes a “return” statement. For example, the following function
returns false because the “finally” clause is the last thing to execute.
function foo() {
try
{
return true;
}
finally {
return false;
}
}
Throwing Exceptions
·
JavaScript allows programmers
to throw their own exceptions via the appropriately named “throw” statement.
This concept can be somewhat confusing to inexperienced developers.
After all, developers strive to write code that is free of errors, yet
the “throw” statement intentionally introduces them. However,
intentionally throwing exceptions can actually lead to code that is easier to
debug and maintain. For example, by creating meaningful error messages it
becomes easier to identify and resolve problems.
·
Several examples of the “throw”
statement are shown below. There is no restriction on the type of data
that can be thrown as an exception. There is also no limit on the number
of times that the same data can be caught and thrown. In other words, an
exception can be thrown, caught, and then thrown again.
throw true;
throw 5;
throw "error message";
throw null;
throw undefined;
throw {};
throw new SyntaxError("useful error
message");
·
While the “throw” statement can
be used with any data type, there are certain benefits to using the built-in
exception types. Firefox, for example, gives special treatment to those
objects by adding debugging information such as the filename and line number
where the exception occurred.
·
As an example
scenario, assume that a division operation occurs somewhere in your
application. Division can be a nuisance because of the possibility of
division by zero. In JavaScript, such an operation results in “NaN”.
This can lead to confusing results that are tricky to debug. Things
would be much simpler if the application complained loudly about the division
by zero. The following “if” statement accomplishes this for us by
throwing an exception.
if (denominator === 0)
throw new Error("Attempted division by zero!");
Of course, it might be more appropriate to
use a “RangeError” as shown below.
if (denominator === 0)
throw new RangeError("Attempted division by zero!");
Custom
Exception Objects
·
We’ve just learned how to
generate customized error messages using the built-in exception types.
However, another approach is to create new exception types by extending
the existing “Error” type. Because the new type inherits from “Error”, it
can be used like the other built-in exception types. While the topic of
inheritance in JavaScript is beyond the scope of this article, a simple
technique is covered here.
·
The following example returns
to the problem of dealing with division by zero. Instead of using an
“Error” or “RangeError” object as we did earlier, we are going to create our
own type of exception. In this example, we are creating the
“DivisionByZeroError” exception type. The function in the example acts as
the constructor for our new type. The constructor takes care of assigning
the “name” and “message” properties. The final two lines of the example
cause the new type to inherit from the “Error” object.
function DivisionByZeroError(message) {
this.name = "DivisionByZeroError";
this.message = (message || "");
}
DivisionByZeroError.prototype = new
Error();
DivisionByZeroError.prototype.constructor =
DivisionByZeroError;
·
The power of jQuery, however,
lies in the fact that the selector syntax is identical to that used in
cascading style sheets (CSS). This means that you can use a rich, familiar
selector syntax to reference any part of the DOM, which becomes a powerful and
efficient way to manipulate the DOM elements.
·
Once you have selected DOM
elements, you will want to manipulate them. This is where jQuery methods come
into play. The jQuery library has a tremendous number of methods that perform
all kinds of useful DOM manipulations. These manipulations are always performed
on the collection of elements returned from the jQuery global function.
·
jQuery supports many methods
for manipulating DOM elements beyond what is shown in Table 2-3. The complete
reference of supported methods is available at
http://api.jquery.com/category/manipulation. Furthermore, jQuery methods can be
chained together so that you can perform several operations in a single line of
code. The following code changes the inner HTML of an element, adds a class,
and then displays the result, all in a single line:
$("displayDiv").html("<p>Hello</p>").addClass("emphasis").show();
Happy programming....
Cheers!
Vamsi