Essentials of Javascript - Cultural View
Essentials of Javascript - Cultural View
Essentials of Javascript - Cultural View
Create successful ePaper yourself
Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.
JavaScript 5<br />
Syntax and semantics<br />
As <strong>of</strong> 2009, the latest version <strong>of</strong> the language is JavaScript 1.8.1. It is a superset <strong>of</strong> ECMAScript (ECMA-262)<br />
Edition 3. Extensions to the language, including partial E4X (ECMA-357) support and experimental features<br />
considered for inclusion into future ECMAScript editions, are documented here. [27]<br />
Example - syntax and semantics<br />
This sample code showcases various JavaScript features. The example can be executed with the following steps: (1)<br />
Copy the code to a file with extension .htm. (2) Use the Mozilla or Firefox browser to open the file.<br />
<br />
LCM Calculator<br />
<br />
<br />
<br />
/* Finds the lowest common multiple <strong>of</strong> two numbers */<br />
function LCMCalculator(x, y) { // constructor function<br />
function checkInt(x) { // inner function<br />
throwing<br />
}<br />
if (x % 1 != 0)<br />
throw new TypeError(x + " is not an integer"); // exception<br />
return x;<br />
//semicolons are optional (but beware since this may cause<br />
consecutive lines to be<br />
}<br />
//erroneously treated as a single statement)<br />
this.a = checkInt(x)<br />
this.b = checkInt(y)<br />
// The prototype <strong>of</strong> object instances created by a constructor is<br />
// that constructor's "prototype" property.<br />
LCMCalculator.prototype = { // object literal<br />
divisor<br />
itself,<br />
gcd : function() { // method that calculates the greatest common<br />
// Euclidean algorithm:<br />
var a = Math.abs(this.a), b = Math.abs(this.b), t;<br />
if (a < b) {<br />
}<br />
t = b; b = a; a = t; // swap variables<br />
while (b !== 0) {<br />
}<br />
t = b;<br />
b = a % b;<br />
a = t;<br />
// Only need to calculate gcd once, so "redefine" this method.<br />
// (Actually not redefinition - it's defined on the instance<br />
// so that this.gcd refers to this "redefinition" instead <strong>of</strong>