JavaScript implementations

As JavaScript and ECMA Script are used in similar context, JavaScript has much more to offer than ECMAScript. It is implemented in the following three parts:

  • Core JavaScript (ECMAScript)
  • Document Object Model (DOM)
  • Browser Object Model (BOM)

Core JavaScript (ECMAScript)

JavaScript supports mobile devices as well as desktop computers; this feature makes it a cross-platform scripting language. However, it is not much useful if used alone, which is why it is used along with server-side languages to make powerful and interactive applications. It can be easily integrated within a web browser environment, enabling users to have complete control over the browser's objects and events.

The core capabilities of JavaScript are also called ECMAScript. ECMAScript is not actually browser-dependent or environment-dependent. It is a set of core language elements that are used in different environments such as ScriptEase and Flash Action Script. Hence, we can say that ECMA Script contains definitions for the following:

  • Language syntax
  • Keywords/reserved words
  • Data types
  • Statements
  • Operators
  • Control structures
  • Objects (for example, array, date, math and so on)

Therefore, ECMAScript defines all of the functions, methods, properties, and objects of a scripting language. Other scripting languages such as JavaScript are implementations of ECMAScript.

ECMAScript is implemented differently in various browsers, after which DOM and BOM are included.

Document object model (DOM)

DOM is an Application Programming Interface(API) for HTML and XML documents. It is a logical structure of the web document. It is a hierarchical tree view of the nodes that are present in the document. The browser translates the document into DOM and only understands it. DOM enables developers to take control over the nodes and to make changes to the document on the fly.

For instance, this is a simple webpage:

<html>
  <head>
    <title>My Web Document</title>
  </head>
  <body>
    <p>Javascript Reference!<p>
  </body>
</html>

Browser object model (BOM)

While DOM deals with the document, Browser Object Model (BOM) deals with the browser window. BOM enables programmers to perform several actions on the browser window, which is not directly related to and has no impact on the HTML document itself. BOM also deals with the browser objects, such as history, screen, navigator, and location.

Note

BOM is implemented differently in different clients.

Client-side JavaScript

JavaScript is primarily known as a client-side scripting language. Any language that is used to write programs or scripts that are executed in a client (any web browser such as Internet Explorer, Safari, Google Chrome, Mozilla Firefox, Opera, and so on) is called a client-side scripting language. These scripts make your HTML look interactive and dynamic. JavaScript enables user to interact with the web page's content and the client window itself.

Adding JavaScript into a web page

Mostly, JavaScript code is embedded into the HTML within the <script> tags and can be viewed by viewing the source of the page. A good practice to embed JavaScript into your page is to place all the scripts in a separate file (a JavaScript file having the .js file extension). Then, this file can be included on the page. When the page is interpreted, it will be treated the same as if it was embedded on the same page.

Tip

The JavaScript files must be of a .js extension.

Since, the client is expecting HTML all the time, anything else such as styles or scripts have to be enclosed in their specific tags; for example:

<style>
  /* all css code */
</style>
<script>
  //all scripts
</script>

The JavaScript interpreter is evoked as soon as the browser's rendering engine discovers any <script> tag.

Most of the time, JavaScript lies within the <head> tags of the web document:

<html>
  <head>
    <title>My First JavaScript Example</title>
    <script type="text/javascript">
      alert("Hello earthlings!");
    </script>
  </head>
  <body>
  </body>
</html>

The type attribute specifies that the code enclosed within these <script> tags is plain code written in JavaScript. It is not compulsory to mention the type attribute. The preceding code can be written without it as well and will work exactly the same.

Although <script> tags can be placed anywhere within an HTML document, another good practice is to place it at the end of the document before closing the </body> tag so that all the pages are loaded before any script executes.

Loading external JavaScript files

Just like external CSS files are included into the web page, JavaScript can also be included into the webpage from external JavaScript files. Let's take a look at the following HTML code:

<html>
  <head>
    <title> My First JavaScript Example </title>
    <script src="external_javascript_Planets.js"></script>
  </head>
  <body>
  </body>
</html>

The src attribute is very similar to that used in the image <img> tags. It just mentions the reference path to the external JavaScript files, which are later included into the page. Do not add any other JavaScript code into the <script> tags, which import external JS files. If needed, place another <script> tag.

Multiple external JS files can also be included, as follows:

<html>
  <head>
    <title> My First JavaScript Example </title>
    <script src="external_javascript_Moon.js"></script>
    <script src="external_javascript_Sun.js"></script>
    <script src="external_javascript)Stars.js"></script>
  </head>
  <body>
  </body>
</html>

Tip

In cases where external JavaScript libraries, such as jQuery and MooTools are used, the order in which the files are included has to be taken care of.

Writing our first program in JavaScript

Don't worry; it is not at all an alien language. It is a high-level language and can be understood very easily as its statements, keywords, and other syntax is based on basic English. The simplest way to learn any programming language is to jump into it and play with its code. To get your feet wet in JavaScript, we will write a very basic JavaScript program.

Prerequisites

The following are the prerequisites that are required to write our first JavaScript program:

  • A web browser
  • A text/code editor
  • A web document

How to do it

  1. Create a index.html file in any code editor you are comfortable with. Copy and paste the following code into your document. It is a simple HTML code:
    <html>
      <head>
        <title> My First JavaScript Example </title>
      </head>
      <body>
        <h1>The Planetary System</h1>
      </body>
    </html>
  2. Create a <script> tag after a <title> tag before closing the </head> tag in the head section:
    <html>
      <head>
        <title> My First JavaScript Example </title>
        <script type="text/javascript"></script>
      </head>
      <body>
        <h1>The Planetary System</h1>
      </body>
    </html>
  3. Insert alert("hello world"); document.write('<h2>This text has been added by JavaScript!</h2>'); within the script tags.
  4. The alert attribute is a JavaScript function that creates a popup with the message written inside the quotes and parentheses. The message is treated as a string passed to the alert function. Similarly, document.write is a JavaScript function that outputs the given string on the webpage.
    <html>
      <head>
        <title> My First JavaScript Example </title>
        <script type="text/javascript">
          alert("Hello Earthlings");
          document.write('<h2>Greetings from Mars!</h2>');
        </script>
      </head>
      <body>
        <h1>The Planetary System</h1>
      </body>
    </html>
  5. Double-click on the index.html file to execute and open it in the browser. A popup will appear with an alert message.

Click on OK to close the alert box and the webpage will be displayed.

This was your first step into the world of JavaScript, although it was very basic and did not show the real power of JavaScript. We will be practicing advanced JavaScript code in the chapters that follow.

Server-side JavaScript

The server is responsible for serving web pages in programming languages. The client sends a request to the server with a command, and the server responds to that client request. Server-side programming is the name given to programs that run on the server. We will study this in further detail in Chapter 11, Extending JavaScript and ECMA Script 6.

The term server-side means that the control over webpages is handled by web servers rather than web pages. Web crossing runs that script and sends information in the form of HTML to each user's browsers.

Rhino and Node are both commonly used to create servers. Server-side scripting is not downloaded to client's browser.

Server side

Server side refers to operations that are performed by the server in a client–server relationship in a computer networking. The term server side can also be understood as anything outside of the browser.

Client side

Anything that is at client side means that it is running inside the web browser.

Scripting with Rhino

Rhino is a JavaScript engine/interpreter developed and written in the Java language and managed by the Mozilla foundation (http://www.mozilla.org/rhino) as open source software. It enables and allows JavaScript program elements to access the complete Java API.

Description

Rhino is a JavaScript open source implementation written in pure Java. Rhino is used to provide scripting to end users. Basically, Rhino converts JavaScript scripts into classes. It is used for server-side programming in JavaScript.

MDN mentions the following: "Scripting Java has many uses. It allows us to write powerful scripts quickly by making use of the many Java libraries available." More information on things such as the this statement would extend the general statement and give some insight into the this statement's implementation and its purpose.

We can use Rhino scripting as a shell for acting like a debugger. This shell runs code in a batch mode. Batch mode refers to batch processing, which means automated processing without human intervention. Batch is the opposite of interactive.

Note

Being open source, Rhino is a free program provided by Mozilla and can be downloaded from http://www.mozilla.org/rhino. Rhino is distributed as a JAR file. To start it with a command line, you can execute the Rhino JAR on a file from the command-line interface:

java -jar rhino1_7R3/js.jar programfiles.js

The 1.7R2 version of Rhino uses ECMAScript 3, while the 1.7R3 version of Rhino partially uses ECMAScript 5. The latest stable release of Rhino is 1.7R5, which was released on January 29, 2015.

Here are a few functions with their usage and description:

Function

Usage

Description

print

print(x)

This is a global print function that prints to the console

version

version(170)

This is used to tell Rhino that we want the JS 1.7 features

load

load(file1,file2…)

This loads and executes one or more files of JavaScript code

readFile

readFile(file)

This reads a text file and returns its contents as a string

readUrl

readUrl(url)

This reads the textual contents of a URL and returns the output as a string

spawn

spawn(f)

This runs f() or load and executes the f file in a new thread

runCommand

runCommand(cmd,[args..])

This runs a system command with zero or more command-line args

quit

quit()

This makes Rhino exit

Here is a simple example that displays the message in the strNote string:

Dim strNote
strNote = "Welcome to Rhino"
Rhino.printstrNote

You can find some more useful scripts at http://www.rhinoscript.org/.

Node.js

Node.js is an implementation of JavaScript that allows JavaScript to run outside the browser and perform OS-based and network-based tasks. It is a runtime interface for JavaScript.

Node uses Google V8, which implements ECMAScript 5 standards, meaning that there is not much difference between the syntax of JavaScript and Node. For example, if you want to print out "Hello World" in the console, you will write the following:

console.log("Hello from Mars!"); //This is same for JavaScript as well.

Description

Node.js is a super fast interface that runs on the Google Chrome V8 engine. Node.js is easy to use, fast, and scalable. Like JavaScript client-side programming, Node.js provides abstraction. So, by this abstraction, Node.js can handle a huge amount of code.

Here is an example or server-side coding in Node.js:

var http=require("http");
http.createServer(function(request,response){
  response.writeHead(200,{"content-type":" text/plain"});
  response.write("Hello from Mars!");
  response.end();
}).listen(8080)
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.117.78.237