Nice book written by David Flanagan.
Few points i want to share from the book
1) JavaScript is an interpreted programming language with object-oriented (OO) capabilities.
2) JavaScript is a case-sensitive language.
3) A function is a piece of executable code that is defined by a JavaScript program or predefined by the JavaScript implementation. Although a function is defined only once, a JavaScript program can execute or invoke it any number of times. A function may be passed arguments, or parameters, specifying the value or values upon which it is to perform its computation, and it may also return a value that represents the results of that computation. JavaScript implementations provide many predefined functions, such as the Math.sin() function that computes the sine of an angle.
4) A function literal looks just like a function definition, except that it does not have to have a name. The big difference is that function literals can appear within other JavaScript expressions. Thus, instead of defining the function square( ) with a function definition:
function square(x) { return x*x; }
it can be defined with a function literal:
var square = function(x) { return x*x; }
Functions defined in this way are sometimes called lambda functions in homage to the Lisp programming language, which was one of the first to allow unnamed functions to be embedded as literal data values within a program. Although it is not immediately obvious why you might choose to use function literals in a program,
5) The scope of a variable is the region of your program in which it is defined. A global variable has global scope; it is defined everywhere in your JavaScript code. On the other hand, variables declared within a function are defined only within the body of the function. They are local variables and have local scope. Function parameters also count as local variables and are defined only within the body of the function.
6) Equality (==) and Identity (===)
The == and === operators check whether two values are the same, using two different definitions of sameness. Both operators accept operands of any type, and both return true if their operands are the same and false if they are different. The === operator is known as the identity operator, and it checks whether its two operands are "identical" using a strict definition of sameness. The == operator is known as the equality operator; it checks whether its two operands are "equal" using a more relaxed definition of sameness that allows type conversions.
7) typeof is a unary operator that is placed before its single operand, which can be of any type. Its value is a string indicating the datatype of the operand.
8) An exception is a signal that indicates that some sort of exceptional condition or error has occurred. To throw an exception is to signal such an error or exceptional condition. To catch an exception is to handle itto take whatever actions are necessary or appropriate to recover from the exception. In JavaScript, exceptions are thrown whenever a runtime error occurs and whenever the program explicitly throws one using the tHRow statement. Exceptions are caught with the TRy/catch/finally statement, which is described in the next section.
9) The Array.join() method converts all the elements of an array to strings and concatenates them. You can specify an optional string that separates the elements in the resulting string. If no separator string is specified, a comma is used. For example, the following lines of code produce the string "1,2,3":
var a = [1, 2, 3]; // Create a new array with these three elements
var s = a.join(); // s == "1,2,3"
10) The Array.slice() method returns a slice, or subarray, of the specified array. Its two arguments specify the start and end of the slice to be returned. The returned array contains the element specified by the first argument and all subsequent elements up to, but not including, the element specified by the second argument. If only one argument is specified, the returned array contains all elements from the start position to the end of the array. If either argument is negative, it specifies an array element relative to the last element in the array. An argument of -1, for example, specifies the last element in the array, and an argument of -3 specifies the third from last element of the array. Here are some examples:
var a = [1,2,3,4,5];
a.slice(0,3); // Returns [1,2,3]
a.slice(3); // Returns [4,5]
a.slice(1,-1); // Returns [2,3,4]
a.slice(-3,-2); // Returns [3]
11) A function is a block of JavaScript code that is defined once but may be invoked, or executed, any number of times. Functions may have parameters, or argumentslocal variables whose value is specified when the function is invoked. Functions often use these arguments to compute a return value that becomes the value of the function-invocation expression. When a function is invoked on an object, the function is called a method, and the object on which it is invoked is passed as an implicit argument of the function. You may already be familiar with the concept of a function under a name such as subroutine or procedure.
Example:
// We begin with the constructor
function Circle(radius) {
// r is an instance property, defined and initialized in the constructor.
this.r = radius;
}
// Circle.PI is a class propertyit is a property of the constructor function.
Circle.PI = 3.14159;
// Here is an instance method that computes a circle's area.
Circle.prototype.area = function( ) { return Circle.PI * this.r * this.r; }
// This class method takes two Circle objects and returns the
// one that has the larger radius.
Circle.max = function(a,b) {
if (a.r > b.r) return a;
else return b;
}
// Here is some code that uses each of these fields:
var c = new Circle(1.0); // Create an instance of the Circle class
c.r = 2.2; // Set the r instance property
var a = c.area( ); // Invoke the area( ) instance method
var x = Math.exp(Circle.PI); // Use the PI class property in our own computation
var d = new Circle(1.2); // Create another Circle instance
var bigger = Circle.max(c,d); // Use the max( ) class method
12) The defer Attribute
As mentioned earlier, a script may call the document.write( ) method to dynamically add content to a document. Because of this, when the HTML parser encounters a script, it must normally stop parsing the document and wait for the script to execute. The HTML 4 standard defines a defer attribute of the <script> tag to address this problem.
If you write a script that does not produce any document outputfor example, a script that defines a function but never calls document.write( )you may use the defer attribute in the <script> tag as a hint to the browser that it is safe to continue parsing the HTML document and defer execution of the script until it encounters a script that cannot be deferred. Deferring a script is particularly useful when it is loaded from an external file; if it is not deferred, the browser must wait until the script has loaded before it can resume parsing the containing document. Deferring may result in improved performance in browsers that take advantage of the defer attribute. In HTML the defer attribute does not have a value; it simply must be present in the tag:
13) The setTimeout( ) method of the Window object schedules a function to run after a specified number of milliseconds elapses. setTimeout( ) returns an opaque value that can be passed to clearTimeout( ) to cancel the execution of the scheduled function.
14) The location property of a window (or frame) is a reference to a Location object; it represents the URL of the document currently being displayed in that window. The HRef property of the Location object is a string that contains the complete text of the URL. The toString( ) method of the Location object returns the value of the href property, so you can use location in place of location.href.
15) The Screen Object
The screen property of a Window object refers to a Screen object that provides information about the size of the user's display and the number of colors available on it. The width and height properties specify the size of the display in pixels. You might use these properties to help decide what size images to include in a document, for example.
The availWidth and availHeight properties specify the display size that is actually available; they exclude the space required by features such as a desktop taskbar. Firefox and related browsers (but not IE) also define availLeft and availTop properties of the screen object. These properties specify the coordinates of the first available position on the screen. If you are writing a script that opens a new browser window
16) Traversing the nodes of a document can be useful, but the real power of the Core DOM API lies in the features that allow you to use JavaScript to dynamically modify documents.
<script>
function sortkids(e) {
// This is the element whose children we are going to sort
if (typeof e == "string") e = document.getElementById(e);
// Transfer the element (but not text node) children of e to a real array
var kids = [];
for(var x = e.firstChild; x != null; x = x.nextSibling)
if (x.nodeType == 1 /* Node.ELEMENT_NODE */) kids.push(x);
// Now sort the array based on the text content of each kid.
// Assume that each kid has only a single child and it is a Text node
kids.sort(function(n, m) { // This is the comparator function for sorting
var s = n.firstChild.data; // text of node n
var t = m.firstChild.data; // text of node m
if (s < t) return -1; // n comes before m
else if (s > t) return 1; // n comes after m
else return 0; // n and m are equal
});
// Now append the kids back into the parent in their sorted order.
// When we insert a node that is already part of the document, it is
// automatically removed from its current position, so reinserting
// these nodes automatically moves them from their old position
// Note that any text nodes we skipped get left behind, however.
for(var i = 0; i < kids.length; i++) e.appendChild(kids[i]);
}
</script>
<ul id="list"> <!-- This is the list we'll sort -->
<li>one<li>two<li>three<li>four <!-- items are not in alphabetical order -->
</ul>
<!-- this is the button that sorts the list -->
<button onclick="sortkids('list')">Sort list</button>
17) A DocumentFragment is a special type of node that does not appear in a document itself but serves as a temporary container for a sequential collection of nodes and allows those nodes to be manipulated as a single object. When a DocumentFragment is inserted into a document (using any of the appendChild(), insertBefore(), or replaceChild() methods of the Node object), it is not the DocumentFragment itself that is inserted, but each of its children.
Hope your enjoy reading this book.
About the Author
David Flanagan is a computer programmer who spends most of his time writing about JavaScript and Java. His books with O'Reilly include Java in a Nutshell, Java Examples in a Nutshell, Java Foundation Classes in a Nutshell, JavaScript: The Definitive Guide, and JavaScript Pocket Reference. David has a degree in computer science and engineering from the Massachusetts Institute of Technology. He lives with his wife and children in the U.S. Pacific Northwest bewteen the cities of Seattle, Washington and Vancouver, British Columbia. David has a blog at www.davidflanagan.com.
No comments:
Post a Comment